1

Is it possible to create a class instance from a plain object without manually mapping plain object values to class instance variables?

For example:

class Person {
  id;
  firstName;
  lastName;
  age;

  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

const hemmingway = {
  id: 1,
  firstName: "Ernest",
  lastName: "Hemmingway",
  age: 62
};

Is it possible to create a Person class instance out of hemmingway without having to resort to manually mapping the keys like this:

constructor(plainObject) {
      this.id = plainObject.id;
      this.firstName = plainObject.lastName;
      this.lastName = plainObject.lastName;
      this.age = plainObject.age;
}

This would be extremely helpful when trying to map network API response objects to class instances.

1 Answer 1

4

After passing the object, use Object.assign to assign all of its properties to the instantiation:

class Person {
  id;
  firstName;
  lastName;
  age;
  constructor(plainObject) {
    Object.assign(this, plainObject);
  }
  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

const hemmingway = {
  id: 1,
  firstName: "Ernest",
  lastName: "Hemmingway",
  age: 62
};
const personHemmingway = new Person(hemmingway);
console.log(personHemmingway.fullName());

Of course, you could also do it outside of the constructor:

class Person {
  id;
  firstName;
  lastName;
  age;
  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

const hemmingway = {
  id: 1,
  firstName: "Ernest",
  lastName: "Hemmingway",
  age: 62
};
const personHemmingway = new Person();
Object.assign(personHemmingway, hemmingway);
console.log(personHemmingway.fullName());

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.