Sometimes, we want to copy some properties from an object in JavaScript.
In this article, we’ll look at how to copy some properties from an object in JavaScript.
How to copy some properties from an object in JavaScript?
To copy some properties from an object in JavaScript, we can use the destructuring syntax.
For instance, we write:
const user = {
id: 123,
firstName: 'John',
lastName: 'Smith'
};
const {
id,
...newUser
} = user;
console.log(newUser);
to get all properties from user
except id
and assign that to newUser
with the destructuring syntax.
The ...
operator returns an object with all the properties except for the ones that has already been destructured.
Therefore, newUser
is {firstName: 'John', lastName: 'Smith'}
.
Conclusion
To copy some properties from an object in JavaScript, we can use the destructuring syntax.