本文介绍了将对象数组中的所有数据求和到新的对象数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的对象数组:
I have an array of objects that looks like this:
var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}]
并且我想对数组中的每个元素求和以生成这样的数组:
and I want to sum each element in the array to produce an array like this:
var result = [{costOfAirtickets: 4000, costOfHotel: 2200}]
我使用了map和reduce函数,但是我只能像这样对单个元素求和:
I have used a map and reduce function but I was able to only sum an individual element like so:
data.map(item => ite.costOfAirtickets).reduce((prev, next)=>prev + next); // 22
目前,这会产生一个单一值,根据初始说明,这不是我想要的.
At the moment this produces a single value which is not what I want as per initial explanation.
有没有办法用Javascript或可能是lodash来做到这一点.
Is there a way to do this in Javascript or probably with lodash.
推荐答案
使用for..in
迭代对象,使用reduce
迭代数组
Using for..in
to iterate object and reduce
to iterate array
var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}];
var result = [data.reduce((acc, n) => {
for (var prop in n) {
if (acc.hasOwnProperty(prop)) acc[prop] += n[prop];
else acc[prop] = n[prop];
}
return acc;
}, {})]
console.log(result)
这篇关于将对象数组中的所有数据求和到新的对象数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!