0

i need to trasform this

const persons = [
  {id:7 ,firstname : "Malcom", lastname: "Reynolds"},
  {id:7, firstname : "Malcom", lastname: "Frye"},
  {id:2,firstname : "Jayne", lastname: "Cobb"}
];

in

const persons_ = [
  {id:7 ,
   firstname : "Malcom",
   item: [{lastname: "Reynolds"},{lastname: "Frye"}]
  } ,
  {id:2,
  firstname : "Jayne", 
  item:[{lastname: "Cobb"}]
  }
];

(grouping by id) can you help me? tks

peraphs i resolve with this code:

     const copyItems = []
persons.forEach(function(item_){
  const found = copyItems.find(element => element.id == item_.id);
  if (!(found)){
    copyItems.push( {id:item_.id,firstname:item_.firstname,item:[{lastname: item_.lastname}]}    )
   }else
   {
    var item ={lastname: item_.lastname}
    copyItems[copyItems.length-1].item.push(item)
   }
})

but i suppose there is a better way.

giorgio
  • 11
  • 1
  • 1
    Does this answer your question? [How can I group an array of objects by key?](https://stackoverflow.com/questions/40774697/how-can-i-group-an-array-of-objects-by-key) It may not be an exact fit, but I hope it helps. – evolutionxbox Jan 11 '22 at 13:35
  • Please add whatever you have tried. Your approach and effort will lead to better response – Tushar Shahi Jan 11 '22 at 13:35

0 Answers0