📌  相关文章
📜  循环遍历对象数组并在它们具有相似键的情况下组合它们 - CSS 代码示例

📅  最后修改于: 2022-03-11 14:47:57.643000             🧑  作者: Mango

代码示例1
//Convert This
var array = [
   {id=1, name = "Orange"},
   {id=1, name = "Blue"},
   {id=1, name = "Green"},
   {id=2, name = "Blue"},
   {id=3, name = "Orange"},
   {id=3, name = "Blue"}
]

//to this
var newArray = [
   {id=1, nameList = [Orange, Blue, Green]},
   {id=2, nameList = [Blue]},
   {id=3, namelist = [Orange, Blue]}
]

var array = [   {id:1, name : "Orange"},   {id:1, name : "Blue"},   {id:1, name : "Green"},   {id:2, name : "Blue"},   {id:3, name : "Orange"},   {id:3, name : "Blue"}]

var result = Object.values(array.reduce((a, c) => {
  (a[c.id] || (a[c.id] = {id: c.id, nameList: []})).nameList.push(c.name);
  return a;
}, {}));

console.log(result);