Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

try this,

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading