-1

I want to add an object and delete two objects in a function

const old1 = [
    {item: "apple", number: 13}
]
const old2 = [
    {item: "apple", number: 13},
    {item: "banana", number: 11},
    {item: "orange", number: 13}
]

First, I want to add an object in the array

const add = {item: "pear", number: 3}

Then I want to check if the array has these elements, if yes, then remove them. Here I want to remove anything "banana" and "orange"

const new2 =[
    {item: "pear", number: 3},
    {item: "apple", number: 13}
]

I tried old1.unshift to add an element. I also tried old2.splice(0,2) to remove elements but it is based of the index order. I should check the item property and remove the relative one.

isherwood
  • 58,414
  • 16
  • 114
  • 157
susu watari
  • 177
  • 1
  • 2
  • 11

2 Answers2

1

You can use Array.push to add the element:

old1.push({item: "pear", number: 3});

And for removing based on a condition - you could put the values you want to remove in an array, then run an Array.filter

let itemsToRemove = ["banana", "orange"]
let filteredItems = old2.filter(o => !itemsToRemove.includes(o.item));
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

For an array of objects I use code similar to this to add/update them.

addUpdateItem(item, arr) {
  let ind = arr.map(i => i.id).indexOf(item.id) //find the position of element if exists
  if(ind != -1) { //this means the item was found in the array

    //normally I would want to update the item if it existed
    Object.assign(arr[ind], item) //update the item

    //but if you wanted to remove the item instead
    arr.splice(ind, 1) //removes the item


  } else {
    arr.push(item)
  }
}
Shawn Pacarar
  • 414
  • 3
  • 12