How To Map Object In Javascript

Mapping is a powerful concept in programming that allows us to transform one data structure into another. In JavaScript, the Array.prototype.map() method is widely used to perform this operation on arrays. However, this method only works for arrays and not for objects. In this blog post, we will explore how to map objects in JavaScript efficiently.

1. Using Object.keys() and Array.prototype.map()

One way to map an object is to use the Object.keys() method, which returns an array of the object’s keys. We can then use the Array.prototype.map() method to iterate over these keys and create a new object.

const originalObject = {
  a: 1,
  b: 2,
  c: 3
};

const mappedObject = Object.keys(originalObject).map((key) => {
  return {
    [key]: originalObject[key] * 2
  };
});

console.log(mappedObject);

In the example above, we create a new object by doubling the values of the original object. The output will be:

[
  { a: 2 },
  { b: 4 },
  { c: 6 }
]

2. Using Object.entries() and Array.prototype.reduce()

Another approach to map an object is using Object.entries() method, which returns an array of key-value pairs. Then, we can use the Array.prototype.reduce() method to iterate over these pairs and create a new object.

const originalObject = {
  a: 1,
  b: 2,
  c: 3
};

const mappedObject = Object.entries(originalObject).reduce((accumulator, [key, value]) => {
  accumulator[key] = value * 2;
  return accumulator;
}, {});

console.log(mappedObject);

In this example, we also create a new object by doubling the values of the original object. The output will be:

{
  a: 2,
  b: 4,
  c: 6
}

3. Custom mapObject() Function

If you find yourself frequently mapping objects, you can create a custom mapObject() function, which takes an object and a mapping function as arguments and returns a new object.

function mapObject(obj, mapFn) {
  return Object.keys(obj).reduce((accumulator, key) => {
    accumulator[key] = mapFn(obj[key], key);
    return accumulator;
  }, {});
}

const originalObject = {
  a: 1,
  b: 2,
  c: 3
};

const mappedObject = mapObject(originalObject, (value, key) => value * 2);

console.log(mappedObject);

With this custom function, the output will also be:

{
  a: 2,
  b: 4,
  c: 6
}

Conclusion

There is no built-in method for mapping objects in JavaScript, but you can achieve it easily using a combination of Object.keys(), Object.entries(), Array.prototype.map(), and Array.prototype.reduce() methods. Also, you can create a custom mapObject() function for frequent use.

Happy coding!