Basically here's what I'm trying to accomplish.
class Person {
constructor (obj) {
this.first = ''
this.last = ''
this.age = ''
if (obj) {
Object.assign(this, ...obj)
}
}
}
const a = new Person()
console.log('Not spreading: ', a)
const b = new Person({ first: 'Alex', last: 'Cory', age: 27 })
console.log('Spreading: ', b)
Is there a way to spread an object like this to populate a class?
The Spread Syntax (also known as the Spread Operator) is another excellent feature of ES6. As the name indicates, it takes an iterable (like an array) and expands (spreads) it into individual elements. We can also expand objects using the spread syntax and copy its enumerable properties to a new object.
Using the spread operator we can easily create a new object with all the same properties of an existing object. const cat = { age: 4 }; const kitten = { ... cat }; // <-- changed kitten. age = 1; console.
Object.assign() The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
Like the docs say, according to the "Rest/Spread Properties proposal", you can't spread object properties onto an array, objects will always spread their properties onto a new object. Likewise, arrays will not spread onto an object, they will only spread onto a new array.
If you're using Object.assign
, you don't use spread notation; just remove the ...
:
class Person {
constructor (obj) {
this.first = ''
this.last = ''
this.age = ''
if (obj) {
Object.assign(this, obj) // <============ No ...
}
}
}
const a = new Person()
console.log('Not spreading: ', a)
const b = new Person({ first: 'Alex', last: 'Cory', age: 27 })
console.log('Spreading: ', b)
There is a proposal (currently at Stage 3, so likely to be in ES2018, and widely supported by transpilers) that does object property spread in object initializers, but that wouldn't apply to your situation where the object already exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With