DEV Community

loading...

JS: use spread to exclude properties

darksmile92 profile image Robin Kretzschmar ・1 min read

I thought I'd share this small trick with you because I find myself looking this up every now and then when I need it.

The spread operator in JavaScript can be very useful.
For example to create a copy of an object:

const firstObject = {id: 0, name: 'John'};
const secondObject = {...firstObject};

console.log(firstObject);
console.log(secondObject);

// { id: 0, name: 'John'}
// { id: 0, name: 'John'}
Enter fullscreen mode Exit fullscreen mode

But did you know you can also use it to except properties when spreading?

const firstObject = {id: 0, firstName: 'John', lastName: 'Smith', age: 77 };
// take every property except age:
const {age, ...secondObject} = {...firstObject};

console.log(firstObject);
console.log(secondObject);
// { id: 0, firstName: 'John', lastName: 'Smith', age: 77 }
// { id: 0, firstName: 'John', lastName: 'Smith' }
Enter fullscreen mode Exit fullscreen mode

The above example will extract age as own variable and will put the remaining in the object secondObject. You can do that with as many properties as you want.

Discussion (3)

pic
Editor guide
Collapse
mschinis profile image
Michael Schinis

Although the gist of the above is correct, the right hand side of the following code creates a copy of the firstObject before extracting age, and creating secondObject, allocating more memory unnecessarily.

const {age, ...secondObject} = {...firstObject};
Enter fullscreen mode Exit fullscreen mode

The following achieves the same outcome, but skips the extra allocation.

const {age, ...secondObject} = firstObject
Enter fullscreen mode Exit fullscreen mode
Collapse
darksmile92 profile image
Robin Kretzschmar Author

Thank you for the explanation, you are absolutely correct about this. That was is more efficient 👍

Collapse
essofyany profile image
essofyany

thanks bro <3