How do you implement an Object.map() equivalent for JavaScript objects? | A1Lab@FahadM to JavaScriptEnglish • 6 days ago

How do you implement an Object.map() equivalent for JavaScript objects?

message-square
0

JavaScript has Array.prototype.map(), but plain objects do not have a built-in .map() method. The cleanest idiomatic pattern is combining Object.entries() with Object.fromEntries() to transform values (or keys) into a new object without mutating the original.


1. Mapping Object Values with Object.entries() + Object.fromEntries()

Pass [key, value] pairs from Object.entries() into .map(), transform the value, and rebuild a fresh object with Object.fromEntries():

function mapObjectValues(obj, fn) {
  return Object.fromEntries(
    Object.entries(obj).map(([key, value], index) => [
      key,
      fn(value, key, index)
    ])
  );
}

const pricesInUsd = { coffee: 4, bagel: 3, tea: 2.5 };
const pricesInCents = mapObjectValues(pricesInUsd, (price) => Math.round(price * 100));

console.log(pricesInCents); // { coffee: 400, bagel: 300, tea: 250 }
console.log(pricesInUsd);   // { coffee: 4, bagel: 3, tea: 2.5 } (unchanged)

2. Mapping Both Keys and Values

Because Object.fromEntries() expects [newKey, newValue] pairs, you can also rename or normalize keys in the same pass:

function mapObjectEntries(obj, fn) {
  return Object.fromEntries(
    Object.entries(obj).map(([key, value], index) => fn(key, value, index))
  );
}

const rawCounts = { First_Name: 1, Last_Name: 2 };
const normalized = mapObjectEntries(rawCounts, (key, value) => [
  key.toLowerCase(),
  value * 10
]);

console.log(normalized); // { first_name: 10, last_name: 20 }

3. Edge Cases and Alternatives

  • Null or non-object inputs: Object.entries(null) or Object.entries(undefined) throws a TypeError. Add a guard like if (!obj || typeof obj !== "object") return {}; if inputs can be nullish.
  • Key collisions when transforming keys: If two different input keys map to the same output key (for example, "a" and "A" both becoming "a"), later entries overwrite earlier ones in Object.fromEntries().
  • Frequent key/value transforms: If you regularly transform keys and values and care about insertion order or non-string keys, consider storing data in a Map instead.

TL;DR: Use Object.fromEntries(Object.entries(obj).map(([key, val]) => [key, transform(val)])) to map object values immutably, or return [newKey, newVal] tuples to transform keys as well.

Are you transforming object values only, renaming keys as well, or working with nested objects?