I have an object:
myObject = { 'a': 1, 'b': 2, 'c': 3 }
I'm looking for a native method similar to Array.prototype.map which can be used like this:
newObject = myObject.map(function (value, label) {
return value * value;
});
// newObject is now { 'a': 1, 'b': 4, 'c': 9 }
Does JavaScript have a map function for such an object? (I want this for Node.JS, so I don't care about cross-browser issues.)
Using JS ES10 / ES2019 How about writing one sentence per line?
Using
Object.entries( )and Object.fromEntries():Write the same thing as a function:
function objMap(obj, func) { return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, func(v)])); } // To square each value you can call it like this: let mappedObj = objMap(obj, (x) => x * x);This function also uses recursion to square nested objects:
function objMap(obj, func) { return Object.fromEntries( Object.entries(obj).map(([k, v]) => [k, v === Object(v) ? objMap(v, func) : func(v)] ) ); } // To square each value you can call it like this: let mappedObj = objMap(obj, (x) => x * x);In ES7/ES2016 you cannot use
Objects.fromEntries, but you can useObject.assignwith Expand operators and Compute key namesSyntax:let newObj = Object.assign({}, ...Object.entries(obj).map(([k, v]) => ({[k]: v * v})));ES6 / ES2015
Object.entriesis not allowed, but you can useObject.keysinstead:let newObj = Object.assign({}, ...Object.keys(obj).map(k => ({[k]: obj[k] * obj[k]})));ES6 also introduced the
for...ofloop, allowing a more imperative style:let newObj = {} for (let [k, v] of Object.entries(obj)) { newObj[k] = v * v; }Array.reduce()
You can also use Object.fromEntries and
Object.assign/Web /JavaScript/Reference/Global_Objects/Array/reduce" rel="noreferrer">reduce To do this:let newObj = Object.entries(obj).reduce((p, [k, v]) => ({ ...p, [k]: v * v }), {});Inherited properties and prototype chain:
In some rare cases, you may need to map a class object that is in its prototype chain . In this case,
Object.keys()andObject.entries()will not work because these functions do not contain a prototype chain.If you need to map inherited properties, you can use
for (key in myObj) {...}.The following are examples of such situations:
const obj1 = { 'a': 1, 'b': 2, 'c': 3} const obj2 = Object.create(obj1); // One of multiple ways to inherit an object in JS. // Here you see how the properties of obj1 sit on the 'prototype' of obj2 console.log(obj2) // Prints: obj2.__proto__ = { 'a': 1, 'b': 2, 'c': 3} console.log(Object.keys(obj2)); // Prints: an empty Array. console.log(Object.entries(obj2)); // Prints: an empty Array. for (let key in obj2) { console.log(key); // Prints: 'a', 'b', 'c' }But please do me a favor and avoid inheritance. :-)
There is no native
mapto theObjectobject, but how about this:var myObject = { 'a': 1, 'b': 2, 'c': 3 }; Object.keys(myObject).forEach(function(key, index) { myObject[key] *= 2; }); console.log(myObject); // => { 'a': 2, 'b': 4, 'c': 6 }