关于前端:对象数组中合并某一属性值相同的元素组成新的子对象数组

51次阅读

共计 344 个字符,预计需要花费 1 分钟才能阅读完成。

举个例子:

let data = [{name:'aaa', id:'1', color:'blue'},
  {name:'aaa', id:'2', color:'green'}
];
let temp = [];
data.forEach(x => {let index = temp.findIndex(y => y.name == x.name);
  if (index == -1) {
    temp.push({
      name: x.name,
      list:[{
        id: x.id,
        color:x.color
      }]
    })
  } else {temp[index].list.push({
      id: x.id,
      color:x.color
    })
  }
})

后果:

[
  name: 'aaa',
  list: [{id:'1', color:'blue'},
    {id:'2', color:'green'}
  ]
]

正文完
 0