Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 737
Alex Cory Avatar asked Sep 18 '17 06:09

Alex Cory


People also ask

Can you spread an object in JavaScript?

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.

How do you add property to an object using the spread operator?

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.

How do you assign object properties?

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.

Can you spread an object into an array JavaScript?

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.


1 Answers

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.

like image 186
T.J. Crowder Avatar answered Oct 12 '22 03:10

T.J. Crowder