Ad

Avoiding Repetition In Destructuring Argument

- 1 answer

I have a function ValidateInteger, that returns an object which looks something like:

{
    Value: "123",
    Neg: false,
    Exp: 3
}

I also have a class which calls this function:

class MyClass {
    constructor(val) {
        {
          Value: this.Value
          Neg: this.Neg
          Exp: this.Exp
        } = ValidateInteger(val);
    }
}

As you can see, there's quite a bit repetition with the this.

My question is there some better syntax to do this, something like:

this.{Value, Neg, Exp} = ValidateInteger(val);

There surely should be some better syntax for this.

Ad

Answer

I think you want Object.assign. It can be used to copy the values of enumerable properties from some objects to another one.

Object.assign(this, ValidateInteger(val));

var ValidateInteger = val => ({
  Value: "123",
  Neg: false,
  Exp: 3
});
class MyClass {
  constructor(val) {
    Object.assign(this, ValidateInteger(val));
  }
}
document.write('<pre>' + JSON.stringify(
  new MyClass() // MyClass { Value: "123", Neg: false, Exp: 3 }
, null, 2) + '</pre>');

Ad
source: stackoverflow.com
Ad