This content originally appeared on Go Make Things and was authored by Go Make Things
Earlier this year, I wrote about both object destructuring and the spread syntax operator.
Yesterday, Angus Croll shared a tweet showing how you can combine the two to remove unwanted properties from an object.
Let’s say you have an object with some information about Merlin the wizard.
let merlin = {
job: 'wizard',
age: '942',
hobbies: ['disappearing', 'seeming aloof'],
spells: ['dancing broomsticks', 'turning into animals'],
height: '6 feet 3 inches',
eyes: 'blue'
};
Now, let’s say you wanted to remove the hobbies
, height
, and eyes
properties from the object.
You could use the delete
operator, like this.
delete merlin.hobbies;
delete merlin.height;
delete merlin.eyes;
It’s a bit verbose, though. And what if you wanted to keep the original intact?
We can use object destructuring and the spread syntax to create a new object with the properties we want, removing the ones we don’t.
let {hobbies, height, eyes, ...merlinAbridged} = merlin;
Now, we have a new merlinAbridged
object containing everything from the original object except the hobbies
, height
, and eyes
properties, which got pulled out into their own variables.
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2021-07-16T14:30:00+00:00) How to remove items from an object with object destructuring and the spread operator. Retrieved from https://www.scien.cx/2021/07/16/how-to-remove-items-from-an-object-with-object-destructuring-and-the-spread-operator/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.