Home > Software design >  How to give a class all the values of a created object in Javascript
How to give a class all the values of a created object in Javascript

Time:07-07

If within a class constructor and I lookup an object that contains many values, how can I make it so that class will obtain all those values?

For example, if this is my object:

const myObject = {
  a: 1,
  b: 2,
  c: 3
}

This is my class:

class MyClass {
  constructor() {
    const object = createMyObject(); // This function returns the above myObject
  }
}

Now, how do I make it so MyClass has all the values of myObject so I can do something like:

const class = new MyClass();
console.log(class.a);
// 1

CodePudding user response:

you can do this:

function createMyObject(){
    return {
        a:1,
        b:2,
        c:3
    }
}
class MyClass{
    constructor(){
        Object.assign(this,createMyObject())
    }
}
const res = new MyClass();
console.log(res.a)
console.log(res.b)
console.log(res.c)

CodePudding user response:

Iterate over the object with Object.entries and assign the key/value pairs to the class.

function createMyObject() {
  return {
    a: 1,
    b: 2,
    c: 3
  };
}

class MyClass {
  constructor() { 
    const object = createMyObject();
    const entries = Object.entries(object);
    for (const [key, value] of entries) {
      this[key] = value;
    }
  }
}

const o = new MyClass();

console.log(o.a);
console.log(o.b);
console.log(o.c);

  • Related