Create Your Own .map() function For Objects

avatar

There are a lot of cases where we need to loop through an object just like an array. There can be hundreds of cases where we need to parse an object and access each child object. There are several workarounds that can be done.

const obj = {  
 vishal: {
   twitter: ‘chandnavishal’,
   name: ‘Vishal Chandna’
 },
 hemant: {
   twitter: ‘forhemant’,
   name: ‘Hemant Gupta’
 },
 kuldeep: {
   twitter: ‘kuldeep’,
   name: ‘Kuldeep Singh’
 }
}

// We can parse this as follows
const arrayOfObjects = Object.keys(obj).map((key, index) => {
 return obj[key];
})

// Or
const arrayOfObjectsValues = Object.values(obj)
const arrayOfObjectsKeys = Object.values(obj)


Using these workarounds over and over again can become very redundant and there is a good amount of code and understanding that you will have to have to get this work.



But what if we are able to write a function just like array.map(), our job would become much easier than it could ever be. Let’s have a look how our obj.map() would look


Object.prototype.map = function(fn) {
 return Object.keys(this).map((key, index) => {
   return fn.call(this, this[key], key, index);
 });
};

// Using .map with objects
obj.map((objectItem, objectKey, ObjectIndex) => {
 console.log(objectItem, objectKey, objectIndex)
});


If you see, we have defined our function inside the Object prototype which would help its instances to have the Object properties. That is the beauty of JavaScript, we have included a function inside the original Object class/function. Just for the demo purposes, I have not added any validations for other arguments.

Let’s understand this step by step —

Object.keys(this).map()

In this, we are taking the call site i.e implicit binding (obj.map()), so that our object to be looped through will be available like this.To learn more about binding — https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/objects-classes/ch2.md

fn.call(this, this[key], key, index);

Now we are taking the function passed by the user and applying the current index arguments to it. At last, returning it to the parent. If you see, we will have three things available inside the function that we pass in .map.First — objectItemSecond — objectKeyThird — objectIndexWe can make use of these whenever we need it.To learn more about call-site — https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/objects-classes/ch2.md

Let’s implement a function to get the length for an object


Object.prototype.length = function() {
 return Object.keys(this).length
}

// Fetch the object length as follows
obj.length() // 3


Now we have a few of the most important methods of Array class available to us natively for objects. Thanks for reading this blog, If you find any value reading it, Give it a thumbs up :)


I have also published this blog on Medium - https://medium.com/@chandna.vishal1234/create-your-own-map-function-for-objects-a1f8a691a450




0
0
0.000
0 comments