DEV Community

Onur Palaz
Onur Palaz

Posted on

Removing object properties from nested array of objects in JavaScript

Removing specific properties from an object can be tricky sometimes, especially if we’d like to remove couple of properties from nested array of objects might be trickier. Here is a solution for that.

Lets say we have an array of objects like here in below;

const cars = [
  { brand: "Toyota", model: "Corolla", year: 2021, color: "Midnight Blue" },
  { brand: "Ford", model: "Escape", year: 2019, color: "Metallic Gray" },
  { brand: "Volkswagen", model: "Golf", year: 2008, color: "Rose Red" },
  { brand: "Honda", model: "Civic", year: 2020, color: "Starlight" },
]
Enter fullscreen mode Exit fullscreen mode

If we’d like to remove the year and color properties from all objects that are nested in our cars array, here is the quick solution,

const newCars = cars.map(({ year, color, ...rest }) => rest)
Enter fullscreen mode Exit fullscreen mode

Let’s also log our new array into the console

console.log(newCars)
Enter fullscreen mode Exit fullscreen mode

Final result will be;

[
  {
    brand: "Toyota",
    model: "Corolla",
  },
  {
    brand: "Ford",
    model: "Escape",
  },
  {
    brand: "Volkswagen",
    model: "Golf",
  },
  {
    brand: "Honda",
    model: "Civic",
  },
]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)