javascript - 合并对象返回带有键和值总和的数组

时间:2018-02-07 00:10:22

标签: javascript arrays object

我有一个像这样的对象,但是我需要操作以返回带有键和数据总和的2个数组。考虑到这些数据可以无限增长。

const data = [
  {
    year: 2017,
    month: 1,
    sources: {
      source1: 50,
      source2: 30,
      source3: 10
    }
  },
  {
    year: 2017,
    month: 2,
    sources: {
      source1: 50,
      source2: 10
    }
  },
  {
    year: 2017,
    month: 3,
    sources: {
      source1: 10,
      source2: 10,
      source3: 1
    }
  }
]

我需要结果和字符串数组以及顺序和源数据的总和

const sources = ["source1", "source2", "source3"]
const data = [160, 50, 1]

1 个答案:

答案 0 :(得分:1)

您可以使用reduce通过迭代每个对象的来源,将Map对象转换为forEach。您展开了地图的keys iterator以获取sources数组,并展开values iterator以获取值数组:

const data = [{"year":2017,"month":1,"sources":{"source1":50,"source2":30,"source3":10}},{"year":2017,"month":2,"sources":{"source1":50,"source2":10}},{"year":2017,"month":3,"sources":{"source1":10,"source2":10,"source3":1}}]

const sourcesMap = data.reduce((m, { sources }) => { 
  Object.entries(sources).forEach(([key, value]) => m.set(key, (m.get(key) || 0) + value))

  return m;
}, new Map())

const sources = [...sourcesMap.keys()]
const values = [...sourcesMap.values()]

console.log(sources)
console.log(values)