[Solved] javascript – merge objects return arrays with the keys and sum of values


You can reduce the objects into a Map by iterating the sources of each object using forEach. You spread the Map’s keys iterator to get the sources array, and spread the values iterator to get the values array:

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)

0

solved javascript – merge objects return arrays with the keys and sum of values