0

Using ES6, I have a class in which I'm defining some variables and a function that will take an object and assing my variables to the values of it. This is repetitive, so is there any way I can use destructuring assingment to achieve this?

class BasicDataMgmt {

  public id: number;
  public name: string;
  public email: string;
  public phone: string;
  public type: string;

  fetchData(data) {
    this.id = data.id;
    this.name = data.name;
    this.email = data.email;
    this.phone = data.phone;
    this.type = data.type;
  }

}
Alexandru Pufan
  • 1,842
  • 3
  • 26
  • 44

1 Answers1

1

It can be

  fetchData(data) {
    Object.assign(this, data);
  }

for unsanitized data. Or

  fetchData({ id, name, ... }) {
    Object.assign(this, { id, name, ... });
  }

for sanitized data.

Using Lodash _.pick is beneficial here for doing Object.assign(this, _.pick(data, ['id', 'name', ...])).

Estus Flask
  • 206,104
  • 70
  • 425
  • 565