乐趣区

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

举个例子:

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'}
  ]
]
退出移动版