0

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
Gary Holiday
  • 3,297
  • 3
  • 31
  • 72

2 Answers2

1

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);
Andy
  • 61,948
  • 13
  • 68
  • 95
  • Yeah, this does work, I was hoping for something simpler like `this = ...object` but I suppose I'm limited to a for loop. – Gary Holiday Jul 06 '22 at 18:13
  • You could do something like `this.props = { ...createMyObject() };` but then you would need to reference `props` in your log: `console.log(o.props.a)` for example. What you can't do is `this = { ...object }` because you'll get an invalid left-hand side assignment error. @GaryHoliday – Andy Jul 06 '22 at 18:21
1

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)
Reza Zand
  • 346
  • 2
  • 6