首页 > 解决方案 > 合并和求和数组对象Javascript

问题描述

我有一个对象数组。如果属性相同,我需要合并数组的元素,tag然后counter对这些对象的属性求和。

这是我的示例数组:

[
    {
        "tag": "#sala",
        "state": {
            "counter": 1
        }
    },
    {
        "tag": "#sala",
        "state": {
            "counter": 2
        }
    }
]

这是合并后数组的样子:

[
    {
        "tag": "#sala",
        "state": {
            "counter": 3
        }
    }
]

标签: javascript

解决方案


您可以使用数组归约函数并在归约回调中使用findIndex来检查累加器数组是否具有具有相同标签的对象。如果找到具有相同标签的对象,则更新该对象中的计数器,否则将当前对象推入累加器数组

let data = [{
    "tag": "#sala",
    "state": {
      "counter": 1
    }
  },
  {
    "tag": "#sala",
    "state": {
      "counter": 2
    }
  }
];
let newData = data.reduce(function(acc, curr) {
  let findTagIndex = acc.findIndex(item => item.tag === curr.tag);
  if (findTagIndex === -1) {
    acc.push(curr)
  } else {
    acc[findTagIndex].state.counter += curr.state.counter
  }
  return acc;
}, []);
console.log(newData)


推荐阅读