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?
If you're using
Object.assign
, you don't use spread notation; just remove the...
(and optionally remove theif
):Note that you don't need the
if
, becauseObject.assign
ignoresnull
orundefined
sources.Not in this example, where you're doing it in the constructor and so the object already exists. There is property spread notation, but it's in object initializers (object literals), so doesn't apply to putting objects in an existing object. That's what
Object.assign
is for.