Home > Blockchain >  Javascript how to assign multiple nested class instances from json object
Javascript how to assign multiple nested class instances from json object

Time:08-25

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?

CodePudding user response:

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)

  • Related