I have an object:
myObject = { 'a': 1, 'b': 2, 'c': 3 }
I am looking for a native method, similar to Array.prototype.map
that would be used as follows:
newObject = myObject.map(function (value, label) {
return value * value;
});
// newObject is now { 'a': 1, 'b': 4, 'c': 9 }
Does JavaScript have such a map
function for objects? (I want this for Node.JS, so I don't care about cross-browser issues.)
To responds more closely to what precisely the OP asked for, the OP wants an object:
to have a map method
myObject.map
,The imho best (measured in terms to "close to what is asked" + "no ES{5,6,7} required needlessly") answer would be:
The code above avoids intentionally using any language features, only available in recent ECMAScript editions. With the code above the problem can be solved lke this:
Besides frowned upon by some, it would be a possibility to insert the solution in the prototype chain like this.
Something, which when done with careful oversight should not have any ill effects and not impact
map
method of other objects (i.e. Array'smap
).If anyone was looking for a simple solution that maps an object to a new object or to an array:
This may not work for all objects or all mapping functions, but it works for plain shallow objects and straightforward mapping functions which is all I needed.
The
map function
does not exist on theObject.prototype
however you can emulate it like soA different take on it is to use a custom json stringify function that can also work on deep objects. This might be useful if you intend to post it to the server anyway as json
You could use
Object.keys
and thenforEach
over the returned array of keys:Or in a more modular fashion:
Note that
Object.keys
returns an array containing only the object's own enumerable properties, thus it behaves like afor..in
loop with ahasOwnProperty
check.There is no native
map
to theObject
object, but how about this:But you could easily iterate over an object using
for ... in
:Update
A lot of people are mentioning that the previous methods do not return a new object, but rather operate on the object itself. For that matter I wanted to add another solution that returns a new object and leaves the original object as it is:
Array.prototype.reduce
reduces an array to a single value by somewhat merging the previous value with the current. The chain is initialized by an empty object{}
. On every iteration a new key ofmyObject
is added with its square as value.