【问题标题】:javascript - merge objects return arrays with the keys and sum of valuesjavascript - 合并对象返回带有键和值总和的数组
【发布时间】:2018-07-17 03:55:11
【问题描述】:

我有一个这样的对象,但我需要操作以返回 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]

【问题讨论】:

  • Array.prototype.reduce() 是你的朋友 =)
  • 我正在努力弄清楚 data[0](假设这是所有 source1 属性的总和?)最终是 60? source2 和 source3 也是如此
  • 获取[60, 40, 1]的逻辑是什么
  • "...我一直在努力解决这个问题。" 发布您一直在努力解决的代码。
  • 您能否发布确切您希望通过您在 sn-p 中提供的数据返回的内容?

标签: javascript arrays object


【解决方案1】:

您可以通过使用forEach 迭代每个对象的源将reduce 对象转换为Map。您传播 Map 的 keys iterator 以获取源数组,并传播 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)

【讨论】:

    猜你喜欢
    • 2020-07-04
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 2020-07-21
    • 2021-06-06
    • 2010-11-10
    • 1970-01-01
    • 2021-10-30
    相关资源
    最近更新 更多