Object MapLoading saved progress…

Object Map

Array.prototype.map builds a new array by running every element through a callback. There is no built-in equivalent for objects, so implement one. objectMap(obj, mapper) returns a new object with the same keys as obj, but every value replaced by mapper(value, key, obj). The original object is left untouched, just like Array.prototype.map never mutates the array it walks.

Signature

// obj:    Record<string, V>           — the source object to read.
// mapper: (value: V, key: string, obj) => U
//         — called once per OWN key; its return value becomes the new value.
// returns: Record<string, U>          — a new object, same keys, mapped values.
function objectMap(obj, mapper): Record<string, U>;

Examples

// Double every value.
objectMap({ a: 1, b: 2 }, (v) => v * 2);
// → { a: 2, b: 4 }
// The mapper also receives the key, so values can be built from both.
objectMap({ a: 1, b: 2 }, (v, k) => k + v);
// → { a: 'a1', b: 'b2' }

Notes

  • Same keys, new values. The result has exactly the keys of obj; only the values change. Values may become any type.
  • The mapper gets three arguments. mapper(value, key, obj) — mirroring Array.prototype.map's (element, index, array). The third argument is the original object.
  • Do not mutate the input. Build a fresh object; leave obj exactly as it was.
  • Own keys only. Map only the object's own enumerable keys. Inherited prototype properties must not appear in the result.
  • Empty in, empty out. objectMap({}, fn) returns {}.
Loading editor…