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

Time:06-04

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

CodePudding user response:

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)

CodePudding user response:

I think you could make it in two steps:

// first remove the "z12" from the array as you requested
array = array.filter(e => e.id !== 'z12')

// and second get the remaining ids
array2 = {
  tab: array.map(e => e.id)
}

CodePudding user response:

splice() method in forEach() cause the problem when the "z12" was removed, the array became

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

BUT the iteration of forEach method did not stop itself. it will continue with index of 1 that just after the z12 was removed so the index of 1 is the "z14", not the "z13".

some knowledge of forEach forEach is BAD!

  • Related