Add property to all objects in array
This question already has an answer here:
使用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));
you can use array.map,
and you should use Number() to convert props to numbers for adding:
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)
链接地址: http://www.djcxy.com/p/12054.html
下一篇: 将属性添加到数组中的所有对象