-3

I have array of objects like this:

const array = [
  {
    name: "Jack",
    age: 25,
    cars: ["bmw", "tesla", "ford", "honda"]
  },
  ...other objects
]

So, how can I remove elements in property cars, like if I could get element "ford" and delete it, then my object will be like this:

[
  {
    name: "Jack",
    age: 25, 
    cars: ["bmw", "tesla", "honda"]
  },
  ...other objects
]
jabaa
  • 5,844
  • 3
  • 9
  • 30
abralinov
  • 3
  • 1
  • Asking how to remove an element from an array means, you didn't do any research. [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – jabaa Jul 27 '22 at 10:32
  • Does this answer your question? [How can I remove a specific item from an array?](https://stackoverflow.com/questions/5767325/how-can-i-remove-a-specific-item-from-an-array). In you case it's array of object so `array[0]['cars']` and apply method on this. – GodWin1100 Jul 27 '22 at 10:33

1 Answers1

3

Simply .map() your array and .filter() every item's car property to remove "ford".

const array = [{
    name: "Jack",
    age: 25,
    cars: ["bmw", "tesla", "ford", "honda"]
  },
  {
    name: "John",
    age: 25,
    cars: ["bmw", "tesla", "ford", "honda"]
  },
]

const result = array.map((item) => ({ ...item,
  cars: item.cars.filter(car => car !== "ford")
}));
console.log(result)
Behemoth
  • 5,389
  • 4
  • 16
  • 40