Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

     

Rest properties with object destructuring

If we want clone an object but remove certain properties we can use this fancy trick:

constuser={firstName:'Homer',lastName:'Simpson',age:40,city:'Springfield',};const{age,...userWithoutAge}=user;
Enter fullscreen modeExit fullscreen mode

Let's see what's insideuserWithoutAge:

// userWithoutAge{firstName:"Homer",lastName:"Simpson",city:"Springfield"}
Enter fullscreen modeExit fullscreen mode

So we have a clone of the original object, but without theage property. Umm, what? 🤔

This is how it works!

First, let's look at a simpler example without the use of the "rest spreading":

const{age,city}=user;console.log(age);// 40console.log(city);// Springfield
Enter fullscreen modeExit fullscreen mode

Here, we're simply destructuring the object to retrieve theage andcity properties as new variables. Cool, so let's see what happens when we look at the original example:

const{age,...userWithoutAge}=user;
Enter fullscreen modeExit fullscreen mode

First, we destructure theage property as we just saw, but also we utilizeobject rest spreading to collect the leftover properties into a variable we can name anything; in this case we call ituserWithoutAge. This object we just created on the fly now contains all the originaluser properties except the age!

Using rest properties for object destructuring assignment is a newer feature added in ECMAScript 2018 and is available in modern browsers.

Links

MDN Article on spread syntax


Check out more #JSBits at my blog,jsbits-yo.com. Or follow me onTwitter!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

3rd Party JS Developer, Blogger, and Competitive Olive Eater
  • Location
    Austin, TX
  • Joined

More fromJS Bits Bill

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp