对象的映射函数(而不是数组) [英] map function for objects (instead of arrays)
问题描述
我有一个对象:
I have an object:
myObject = { 'a': 1, 'b': 2, 'c': 3 }
我正在寻找一个本地方法,类似于 Array。 prototype.map
,它的用法如下:
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 }
JavaScript是否具有对象的这种 map
函数? (我想要Node.JS,所以我不在乎跨浏览器的问题。)
Does JavaScript have such a map
function for objects? (I want this for Node.JS, so I don't care about cross-browser issues.)
推荐答案
没有原生的 map
到 Object
对象,但是这样做如何:
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;
}
}
更新
很多人都提到前面的方法不会返回一个新的对象,而是对对象本身进行操作。对于这个问题,我想添加另一个解决方案,返回一个新的对象,并保留原来的对象:
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 code>
通过将前一个值与当前值进行某种合并来将数组减少为单个值。链由空对象 {}
初始化。在每次迭代时,都会添加一个新的 myObject
键,并将其平方作为值。
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.
这篇关于对象的映射函数(而不是数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!