Tag: spread

Spread and Exclude

Spread and Exclude

The other day I wanted to log out some values of a large object. But one particular property was massive and not needed. So how could I pass all of the original object minus that one property that was going to get in the way?
As in how to exclude a single property from a object.

Solution:

It’s a very simple and I think elegant solution. so here it is.

Using the spread operator you can list the specific items to copy first (these will then be excluded) then use the … rest operator to copy the remaining items.

That’s it! It telling your code what to specifically copy first, those will then not be included when you use the rest operator. Brilliant!

const bigObject = {a: 1, b: 2, c: 3, d: 4, e: 5, f: 6};
const { a, ...copiedAndExcluded } = bigObject;
// copiedAndExcluded is now the same as bigObject, expect it doesn't have the property 'a'.

Also in my case the bigObject was a property of something else, which at times may have been undefined. This will cause an error, as you can’t spread undefined.

const parentObject = { a: 1, bigObject = undefined, c: 3, d: 4};
const { a, ...copiedAndExcluded } = parentObject.bigObject || {};
// 'a' and 'copiedAndExcluded' will be undefined

The `|| {}` will make sure that the code doesn’t try to spread the value of undefined (as that will throw an error). You can however spread an empty object. The values that come out will be undefined, which in my case was just fine.