Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Matt Crowder
Matt Crowder

Posted on

     

JavaScript object spread explained

If you want to update a piece of an object while creating a new object, then the spread syntax is the way to go.

When you see..., you should just think of flattening the object.

When you see this:

constmetadata={first:"Matt",last:"Crowder"};constupdatedMetadata={...metadata,last:"Jenkins"};
Enter fullscreen modeExit fullscreen mode

You should just seeupdatedMetadata as such:

constupdatedMetadata={first:"Matt",last:"Crowder",last:"Jenkins"};
Enter fullscreen modeExit fullscreen mode

Key/value assignments are read from top to bottom, so the last key's value will take priority in setting the value.

And nowupdatedMetadata will have the value of:

{first:"Matt",last:"Jenkins"}
Enter fullscreen modeExit fullscreen mode

So the spread flattens out the object wherever you place it, so if we had placed the spread metadataafterlast: "Jenkins", then we would get no updates!

constmetadata={first:"Matt",last:"Crowder"};constupdatedMetadata={last:"Jenkins",...metadata};// results inconstupdatedMetadata={last:"Jenkins",first:"Matt",last:"Crowder"};// which gives us nothing
Enter fullscreen modeExit fullscreen mode

So be careful where you place your spread syntax!

Top comments(1)

Subscribe
pic
Create template

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

Dismiss
CollapseExpand
 
rogasper profile image
rogasper
Student
  • Location
    Indonesia
  • Work
    Student
  • Joined

Nice, i know understand

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

Software Engineer at Veeva
  • Location
    Austin, TX
  • Education
    CS Degree
  • Joined

More fromMatt Crowder

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