如何使用 reduce(下划线?)对对象数组中的某些值求和
How can I sum some of the values in an object array using reduce (underscore?)
我有以下 JSON 结构。
var fooArray =
[{ name: 'firstValue',
price1: 20,
price2: 11
},
{ name: 'secondValue',
price1: 54,
price2: 13
},
{ name: 'thirdValue',
price1: 3,
price2: 6
}]
如何求和对象数组中的值? (除了使用 for
循环)
{price1: 77,
price2: 28}
您可以使用对属性求和的函数对数组进行归约:
_.reduce(fooArray, function (accum, x) {
return {
price1: x.price1 + accum.price1,
price2: x.price2 + accum.price2
};
});
这类似于@MatthewMcveigh 的回答,但生成的对象没有虚假 name
属性:
_.reduce(fooArray, function (accum, x) {
return {
price1: x.price1 + accum.price1,
price2: x.price2 + accum.price2
};
}, {price1: 0, price2: 0});
我有以下 JSON 结构。
var fooArray =
[{ name: 'firstValue',
price1: 20,
price2: 11
},
{ name: 'secondValue',
price1: 54,
price2: 13
},
{ name: 'thirdValue',
price1: 3,
price2: 6
}]
如何求和对象数组中的值? (除了使用 for
循环)
{price1: 77,
price2: 28}
您可以使用对属性求和的函数对数组进行归约:
_.reduce(fooArray, function (accum, x) {
return {
price1: x.price1 + accum.price1,
price2: x.price2 + accum.price2
};
});
这类似于@MatthewMcveigh 的回答,但生成的对象没有虚假 name
属性:
_.reduce(fooArray, function (accum, x) {
return {
price1: x.price1 + accum.price1,
price2: x.price2 + accum.price2
};
}, {price1: 0, price2: 0});