decompose object to this attributes

Viewed 135

I am trying to decompose an object into attributes as follows;

let example = {name: 'Fred', age:20}
const {name, age} = example;

But, I would like it to do to the this.name, and this.age of the class it is in. Something like;

class Test = {

   name: ''
   age: null

   constructor(example) {

       {this.name, this.age} = example;

   }


}

Is this possible?

1 Answers

It is possible to assign value to objects using destructuring. It is definitely NOT recommended. You can see why:

class Test {
  name = ''
  age = null
  constructor(example) {
    ({ name: this.name, age: this.age } = example) // <- dont't forget the parenthesis
  }
}

console.log(
  new Test({ name: 'name', age: 10 })
)

If the properties of example and the class are same, you can just use Object.assign

class Test {
  name = ''
  age = null
  constructor(example) {
    Object.assign(this, example)
  }
}

console.log(
  new Test({ name: 'name', age: 10 })
)

Related