首页 > 解决方案 > 按键值重新组合数组中对象的有效方法

问题描述

我有一个对象数组。这些对象有两个道具:字符串类型的属性“标签”和一个数组的道具“检测”。我需要一个可以将相同标签的对象分组并合并相对数组的函数。

例如:

const list = [
    { label: 'cat', detections: ['a','b'] },
    { label: 'horse', detections: ['c','d'] },
    { label: 'cat', detections: ['e','f'] }
]

会成为:

const result = groupMergeByLabel(list)
// value logged would be => [
    { label: 'cat', detections: ['a','b','e','f'] },
    { label: 'horse', detections: ['c','d'] }
]

标签: javascriptarrays

解决方案


你可以使用reduce

const list = [
    { label: 'cat', detections: ['a','b'] },
    { label: 'horse', detections: ['c','d'] },
    { label: 'cat', detections: ['e','f'] }
];

const result = list.reduce((res, {label, detections}) => {
  const existing = res.find(x => x.label === label);
  if (existing) {
    existing.detections.push(...detections);
  } else {
    res.push({label, detections});
  }
  return res;
}, []);

console.log(result);


推荐阅读