map function for objects (instead of arrays)
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.)
There is no native map
to the Object
object, but how about this:
Object.keys(myObject).map(function(key, index) {
myObject[key] *= 2;
});
console.log(myObject);
// => { 'a': 2, 'b': 4, 'c': 6 }
But you could easily iterate over an object using for ... in
:
for(var key in myObject) {
if(myObject.hasOwnProperty(key)) {
myObject[key] *= 2;
}
}
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:
var newObject = Object.keys(myObject).reduce(function(previous, current) {
previous[current] = myObject[current] * myObject[current];
return previous;
}, {});
console.log(newObject);
// => { 'a': 1, 'b': 4, 'c': 9 }
console.log(myObject);
// => { 'a': 1, 'b': 2, 'c': 3 }
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 of myObject
is added with its square as value.
How about a one liner with immediate variable assignment in plain JS ( ES6 / ES2015 ) ?
Making use of spread operator and computed key name syntax:
let newObj = Object.assign({}, ...Object.keys(obj).map(k => ({[k]: obj[k] * obj[k]})));
jsbin
Another version using reduce:
let newObj = Object.keys(obj).reduce((p, c) => ({...p, [c]: obj[c] * obj[c]}), {});
jsbin
First example as a function:
const oMap = (o, f) => Object.assign({}, ...Object.keys(o).map(k => ({ [k]: f(o[k]) })));
// To square each value you can call it like this:
let mappedObj = oMap(myObj, (x) => x * x);
jsbin
If you want to map a nested object recursively in a functional style, it can be done like this:
const sqrObjRecursive = (obj) =>
Object.keys(obj).reduce((newObj, key) =>
(obj[key] && typeof obj[key] === 'object') ?
{...newObj, [key]: sqrObjRecursive(obj[key])} : // recurse.
{...newObj, [key]: obj[key] * obj[key]} // square val.
,{})
jsbin
Or more imperatively, like this:
const sqrObjRecursive = (obj) => {
Object.keys(obj).forEach(key => {
if (typeof obj[key] === 'object') obj[key] = sqrObjRecursive(obj[key]);
else obj[key] = obj[key] * obj[key]
});
return obj;
};
jsbin
Since ES7 / ES2016 you can use Object.entries
instead of Object.keys
eg like this:
let newObj = Object.assign(...Object.entries(obj).map(([k, v]) => ({[k]: v * v})));
Inherited properties and the prototype chain:
In some rare situation you may need to map a class-like object which holds properties of an inherited object on its prototype-chain. In such cases Object.keys()
won't work, because Object.keys()
does not enumerate inherited properties. If you need to map inherited properties, you should use for (key in myObj) {...}
.
Here is an example of an object which inherits the properties of another object and how Object.keys()
doesn't work in such scenario.
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.
for (key in obj2) {
console.log(key); // Prints: 'a', 'b', 'c'
}
jsbin
However, please do me a favor and avoid inheritance. :-)
没有本地的方法,但lodash#mapValues会出色地完成这项工作
_.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; });
// → { 'a': 3, 'b': 6, 'c': 9 }
链接地址: http://www.djcxy.com/p/53580.html
下一篇: 对象的映射函数(而不是数组)