Does JavaScript has map function for objects (instead of arrays)?

JavaScript does not have a built-in map() function for objects** like it does for arrays, but you can achieve similar behavior using methods like Object.keys(), Object.values(), or Object.entries(), combined with Array.map().

Here are common workarounds to “map” over an object’s properties:

1. Using Object.entries() + Array.map()

Convert the object into an array of [key, value] pairs, map over them, and convert back to an object:

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

const mappedObj = Object.fromEntries(
  Object.entries(obj).map(([key, value]) => [key, value * 2])
);

console.log(mappedObj); // { a: 2, b: 4, c: 6 }

2. Using Object.keys() + Array.map()

Iterate over the object’s keys and create a new object:

const obj = { x: 10, y: 20, z: 30 };

const mappedObj = Object.keys(obj).reduce((acc, key) => {
  acc[key] = obj[key] * 2;
  return acc;
}, {});

console.log(mappedObj); // { x: 20, y: 40, z: 60 }

3. Using a for...in Loop

Manually iterate over the object’s keys:

const obj = { id: 1, name: "Alice" };
const mappedObj = {};

for (const key in obj) {
  if (obj.hasOwnProperty(key)) {
    mappedObj[key] = String(obj[key]); // Example: Convert values to strings
  }
}

console.log(mappedObj); // { id: "1", name: "Alice" }

4. Map Object Values to an Array

If you want to return an array (like Array.map()):

const obj = { a: 100, b: 200 };

const mappedArray = Object.values(obj).map(value => value / 10);
console.log(mappedArray); // [10, 20]

Key Notes

  • Object → Array → Object: Most solutions involve converting the object to an array, mapping over it, then converting back.
  • Immutability: The original object remains unchanged.
  • Helper Libraries: Use utility libraries like Lodash’s _.mapValues() for a cleaner syntax:
  const _ = require('lodash');
  const mapped = _.mapValues({ a: 1, b: 2 }, v => v * 2); // { a: 2, b: 4 }

When to Use Which?

  • Object.entries(): Best for modifying both keys and values.
  • Object.keys()/Object.values(): Use when you only need keys/values.
  • for...in: For legacy environments (pre-ES2017) or specific edge cases.

While JavaScript lacks a native map() for objects, these patterns provide the same flexibility.

Leave a Reply

Your email address will not be published. Required fields are marked *