Javascript 为数组中的所有对象添加属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36677787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add property to all objects in array
提问by Miguel Moura
I have the following array of objects:
我有以下对象数组:
var array = [ {'a': '12', 'b':'10'}, {'a': '20', 'b':'22'} ];
How can I add a new property c = b - a
to all objects of the array?
如何c = b - a
向数组的所有对象添加新属性?
回答by maioman
you can use array.map,
你可以使用array.map,
and you should use Number() to convert props to numbers for adding:
您应该使用 Number() 将道具转换为数字以进行添加:
var array = [ {'a': '12', 'b':'10'}, {'a': '20', 'b':'22'} ];
var r = array.map( x => {
x.c = Number(x.b) - Number(x.a);
return x
})
console.log(r)
And, with the support of the spread operator, a more functional approach would be:
并且,在扩展运算符的支持下,更实用的方法是:
array.map(x => ({
...x,
c: Number(x.a) - Number(x.b)
}))
回答by isvforall
Use forEach
function:
使用forEach
功能:
var array = [{ 'a': '12', 'b': '10' }, { 'a': '20', 'b': '22' }];
array.forEach(function(e) { e.c = +e.b - +e.a });
document.write(JSON.stringify(array));