Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
How to give a class all the values of a created object in Javascript

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
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!