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:
This function also uses recursion to square nested objects:
In ES7/ES2016 you cannot use
Objects.fromEntries
, but you can useObject.assign
with Expand operators and Compute key namesSyntax:ES6 / ES2015
Object.entries
is not allowed, but you can useObject.keys
instead:ES6 also introduced the
for...of
loop, allowing a more imperative style:Array.reduce()
You can also use Object.fromEntries and
Object.assign
/Web /JavaScript/Reference/Global_Objects/Array/reduce" rel="noreferrer">reduce To do this: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:
But please do me a favor and avoid inheritance. :-)
There is no native
map
to theObject
object, but how about this: