Removing object properties from nested array of objects in JavaScript
Onur Palaz
Posted on August 4, 2024
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" },
]
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)
Let’s also log our new array into the console
console.log(newCars)
Final result will be;
[
{
brand: "Toyota",
model: "Corolla",
},
{
brand: "Ford",
model: "Escape",
},
{
brand: "Volkswagen",
model: "Golf",
},
{
brand: "Honda",
model: "Civic",
},
]
💖 💪 🙅 🚩
Onur Palaz
Posted on August 4, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.