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

92
Views
Javascript how to assign multiple nested class instances from json object

I have a json with the below format:

let js = {
      "a": 1,
      "b": [
        {
          "h": "example",
          "v": 12
        },
        {
          "h": "example1",
          "v": 23
        }
      ]
    }

I have a class that takes in this json from constructor turning it into an instance of this class:

class A{
    constructor (json){
        Object.assign(this, json)
    }
}

This works well with:

a = new A(js)
console.log(f.a)

I have a second class which has the format of the inner list b:

class B {
    construtor(json){
        Object.assign(this, json)
    }
}

How can I instantiate class B from the object passed to A so that f.b[0] and f.b[1] above would be of type B?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

try this,

let js = {
  "a": 1,
  "b": [{
      "h": "example",
      "v": 12
    },
    {
      "h": "example1",
      "v": 23
    }
  ]
}
class A {
  constructor(json) {
    // create a new b array with instances of class B.
    json.b = json.b.map(json => new B(json))
    Object.assign(this, json)
  }
}
class B {
  constructor(json) {
    Object.assign(this, json)
  }
}

const a = new A(js);
console.log({a});
console.log('is a.b[0] instance of class B?', a.b[0] instanceof B)

about 4 years ago · Santiago Trujillo 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!