【问题标题】:How do you merge an array of objects based on equal property values? [duplicate]如何基于相等的属性值合并对象数组? [复制]
【发布时间】:2020-07-27 07:51:51
【问题描述】:

我有以下问题。我有一个对象数组,我想添加日期相等的值。

这是起始数组:

0: {date: "07-04-2020", value: 10}
1: {date: "10-04-2020", value: 20}
2: {date: "07-04-2020", value: 30}
3: {date: "14-04-2020", value: 60}

它应该导致以下结果:

0: {date: "07-04-2020", value: 40}
1: {date: "10-04-2020", value: 20}
3: {date: "14-04-2020", value: 60}

我尝试了一些高阶函数,例如过滤器、映射和归约,但我一无所知。

【问题讨论】:

  • 欢迎来到 Stack Overflow!请使用tour(您将获得徽章!)并通读help center,尤其是How do I ask a good question? 您最好的选择是进行研究,search 以获取有关 SO 的相关主题,然后试一试. 如果您在进行更多研究和搜索后遇到困难并且无法摆脱困境,请发布您的尝试minimal reproducible example,并具体说明您遇到的问题。人们会很乐意提供帮助。
  • stackoverflow.com/questions/43281272/… 和其他几个来自this search。更多关于搜索here
  • var foo = [{date: "07-04-2020", value: 10}, {date: "10-04-2020", value: 20}, {date: "07-04-2020", value: 30}, {date: "14-04-2020", value: 60}]; var bar = {}; foo.forEach(i => { if(bar[i.date]) { bar[i.date] += i.value} else {bar[i.date] = i.value} }) - 然后将它们映射回您的原始结构
  • Object.keys(bar).map(k => { return {date: k, value: bar[k]}})映射回来

标签: javascript arrays object


【解决方案1】:

这对你有用吗?

let myArr = [{
    date: "07-04-2020",
    value: 10
  },
  {
    date: "10-04-2020",
    value: 20
  },
  {
    date: "07-04-2020",
    value: 30
  },
  {
    date: "14-04-2020",
    value: 60
  },
]

function sum(arr) {
  let result = [];
  let temp = {};

  arr.forEach((row) => {
    temp[row.date] = temp[row.date] ? temp[row.date] + row.value : row.value;
  });

  Object.entries(temp).forEach((dateValue) => {
    result.push({
      date: dateValue[0],
      value: dateValue[1]
    });
  });

  return result;
}
console.log(sum(myArr));

【讨论】:

    【解决方案2】:

    你可以使用Array.reduce:

    [...].reduce((acc, next) => {
      // Check if an item with the given date exists
      const existingItem = acc.find(item => item.date === next.date);
      // If not, add the new one to the array
      if (!existingItem) {
        return [...acc, next];
      }
      // If there's one already, mutate the value property and return everything
      existingItem.value += next.value;
      return acc;
    }, []);
    

    【讨论】:

      猜你喜欢
      • 2021-03-29
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      • 2016-11-02
      • 2022-01-06
      • 1970-01-01
      相关资源
      最近更新 更多