将对象数组中的所有数据汇总到新的对象数组中 [英] Sum all data in array of objects into new array of objects

查看:38
本文介绍了将对象数组中的所有数据汇总到新的对象数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的对象数组:

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 => item.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)

这篇关于将对象数组中的所有数据汇总到新的对象数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆