我需要根据对象的属性合并数组的值,typescript

bwleehnv  于 2023-01-27  发布在  TypeScript
关注(0)|答案(1)|浏览(143)

我有一个数组,如下所示:

example = [{
"prop": "test",
"propId": [1]
},
{
"prop": "test",
"propId": [2]
},
{
"prop": "test",
"propId": [3]
},
{
"prop": "test2",
"propId": [4]
},
{
"prop": "test2",
"propId": [5]
" 
]

然后我需要合并并根据该值推送propId的值,我期望的输出如下所示:

output = [
{
"prop": "test",
"propId": [1, 2 ,3]
},
{
"prop":"test2",
"propId": [4, 5]
}]

我不能硬编码test或test2,这些是来自API的动态值,示例只是一个简短的版本

oknwwptz

oknwwptz1#

一个简单的减速器功能就可以了

const example = [
  {
    prop: "test",
    propId: [1]
  },
  {
    prop: "test",
    propId: [2]
  },
  {
    prop: "test",
    propId: [3]
  },
  {
    prop: "test2",
    propId: [4]
  },
  {
    prop: "test2",
    propId: [5]
  }
];

const groupProps = (propArr) =>
  propArr.reduce((result, el) => {
    const { prop, propId } = el;
    const found = result.find((el) => el.prop === prop);
    found ? found.propId.push(...propId) : result.push(el);
    return result;
  }, []);

console.log(groupProps(example));

相关问题