Create Copy Of JavaScript Object Except For Certain Properties
May 15, 2020 by Andreas Wik
Here’s how to create a copy of an object in JavaScript, but without certain properties.
Let’s say I want to make a copy of this statueObj object below, BUT I don’t want the company property in my new object.
const statueObj = {
city: "Sydney",
height: 238,
material: "bronze",
company: "Haddonstone"
}
The following code will do just this, using destructuring. We assign the company property to its own variable and assign all of the rest of the properties in statueObj to a new object named newStatueObj.
const {company, ...newStatueObj} = statueObj
console.log(newStatueObj);
/*
Prints:
{
city: "Sydney",
height: 238,
material: "bronze"
}
*/
You could do this with more than just one property. Let’s remove city as well:
const {company, city, ...newStatueObj} = statueObj
console.log(newStatueObj);
/*
Prints:
{
height: 238,
material: "bronze"
}
*/
Toodles!