Arrays have map; objects do not. Yet the need is everywhere: prices keyed by product that must be shown with tax, settings keyed by name that must be turned into labels, an API response keyed by id that must be reshaped. mapValues keeps the keys and transforms each value.
Write mapValues(object, fn) in map-values.js. It returns a new plain object with the same keys as object, where each value is fn(value, key, object).
Each key of the result holds fn(value, key, object) for that key; fn receives the value, the key and the object itself, once per key.
The result is a new object, and the input is unchanged.
The keys keep their order: the same order as Object.keys of the input (integer-like keys first, ascending, then the others in the order they were added).
Only own enumerable string keys count: inherited properties, non-enumerable properties and symbol keys are left out.
An empty object gives an empty object, and a key whose new value is undefined is still there.
A key named __proto__ (as JSON.parse can produce) is an ordinary key in the result; the result's prototype stays Object.prototype.
The result is a plain object even when the input is a class instance, an object without a prototype, or an array.
Each value is read once.
It throws a TypeError when fn is not a function (even for an empty object), and when object is null or undefined.
constchild= Object.create({ inherited: 1 });child.own =2;mapValues(child, (value) => value *10); // { own: 20 }: inherited keys are left out
JAVASCRIPT
constparsed=JSON.parse('{"__proto__": 1}');mapValues(parsed, (value) => value +1); // an object with an own key "__proto__" holding 2mapValues({ a: 1 }, "not a function"); // TypeError