对象数组中,合并某一属性值相同的元素,组成新的子对象数组

举个例子:

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'}
  ]
]

你可能感兴趣的:(前端,javascript)