-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
  • 46,000
  • 15
  • 100
  • 132
susu watari
  • 137
  • 1
  • 7
  • From which are are you removing? – Amit Das May 15 '19 at 20:26
  • Possible duplicate of [How to append something to an array?](https://stackoverflow.com/questions/351409/how-to-append-something-to-an-array) – isherwood May 15 '19 at 20:30
  • Possible duplicate of https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element-from-an-array-in-javascript – isherwood May 15 '19 at 20:31
  • Possible duplicate of https://stackoverflow.com/questions/4775722/how-to-check-if-an-object-is-an-array – isherwood May 15 '19 at 20:31
  • susu watari, please ask just one question per post. You have three up there, I think. [Take the tour](https://stackoverflow.com/tour) to learn more. – isherwood May 15 '19 at 20:33
  • Thanks isherwood, I can do it separately but somehow it doesn't work together. – susu watari May 15 '19 at 20:43

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
  • 99,730
  • 13
  • 150
  • 152
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
  • 311
  • 1
  • 11