Search code examples
javascriptclassspread-syntax

How to spread an object into a classes properties in JavaScript


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?


Solution

  • If you're using Object.assign, you don't use spread notation; just remove the ... (and optionally remove the if):

    class Person {
        constructor (obj) {
            this.first = "";
            this.last = "";
            this.age = ""; // Consider a number rather than ""?
    
            // (No need for the `if`)
            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);
    .as-console-wrapper {
        max-height: 100% !important;
    }

    Note that you don't need the if, because Object.assign ignores null or undefined sources.

    Is there a way to spread an object like this to populate a class?

    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.