Answers for "Loop Over Array of Objects and Combine them if they have similar keys"

CSS
0

Loop Over Array of Objects and Combine them if they have similar keys

//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);
Posted by: Guest on July-07-2021

Code answers related to "Loop Over Array of Objects and Combine them if they have similar keys"

Browse Popular Code Answers by Language