Object.assign() is an Object prototype method that is commonly used to copy objects in Javascript. That is a view from 30,000 feet that doesn’t cover many of the nuances that we will cover in this podcast. For Meteor users that often use the Underscore.js library you might use _.extend or _.extendOwn. Listen in to this short Javascript pro tip for more on this.
Code Example
const objA = { a: 1, b: 2, c: { d: 3 } }; const objB = Object.assign({}, objA); // or Object.assign(objA) console.log(objB); // { a: 1, b: 2, c: { d: 3 } } // shows that assign returns a shallow copy with references to nested objects objA.c = 1234; console.log(objB); // { a: 1, b: 2, c: 1234 } // demonstrates target object which is the first source in Object.assign is modified in place and the later the source in the list it takes priority over previously assigned object properties const objC = { a: 1, b: 2, c: { d: 3 } }; const objD = Object.assign(objC, { b: 1234} ); console.log(objC); // { a: 1, b: 1234, c: { d: 3 } }
External Resources:
MDN Object.assign()
Underscore.js _.extend()
Podcast: Play in new window | Download | Embed
Subscribe: Apple Podcasts | Android | Google Play | Stitcher | TuneIn | RSS
Leave a Reply