Search code examples
javascripttypescriptlodash

How can I delete a item from an array and push a result?


I have this array:

 [
  {
   "id": "z12",
   "val": "lu",
   "val2": "1",
  },
  {
   "id": "z13",
   "val": "la",
   "val2": "2",
  },
  {
   "id": "z14",
   "val": "lo",
   "val2": "3",
  },
]

I have second

    array2 = {
      tab: [],
    }

i do in my typeScript :

   array.forEach((item, index)=>{
    if(item.id === z12){
      array.splice(index, 1);
    }else{
      array2.tab.push(item.id);
    }
});

I should normally have: tab: [z13,z14] but it does not work


Solution

  • You can filter and map directly.

    const array = [{ "id": "z12", "val": "lu", "val2": "1", }, { "id": "z13", "val": "la", "val2": "2", }, { "id": "z14", "val": "lo", "val2": "3", },];
    
    const array2 = {
      tab: array.filter(e => e['id'] != "z12").map(e => e['id']),
    }
    
    console.log(array2)