codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Use ES7 Object Rest Operator to Omit Properties

--

I was perusing the Airbnb JavaScript Style Guide today when I came across an intriguing pattern that cleverly uses the ES7 Object Rest Spread operator to omit properties from an object.

Ready? Here it is:

const myObject = {
a: 1,
b: 2,
c: 3
};
const { a, ...noA } = myObject;
console.log(noA); // => { b: 2, c: 3 }

This confused me at first, so I’ll explain. We are using Object Destructuring in conjunction with the Object Rest Spread operator to separate our large myObject into separate parts a and noA.

It’s essentially creating two new const variables and storing separate parts of our object in them. The rest operator tells the script to put any other not explicitly defined property in the last variable. So all we have to do is destructure all the properties we don’t want — a — so we are left with just the properties we do want stored in our last variable — noA.

“Perfection is achieved … when there is nothing left to take away.” — Antoine de Saint Exupéry

What’s especially great about this pattern is, unlike delete, we aren’t mutating the original object, myObject, nor are we removing the reference a, so we can rest assured we haven’t accidentally broken something that is using myObject or a.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Responses (18)

Write a response