0

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?

bcsta
  • 1,963
  • 3
  • 22
  • 61
  • 2
    [There's no such thing as a "JSON object"](https://www.json.org/json-en.html), and there's no JSON in your question. – Andreas Aug 24 '22 at 13:29
  • 1
    _"which is what JSON stands for"_ - No. Absolutely not. Did you have a look at the link in my comment? Or check this one: [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Aug 24 '22 at 13:39
  • 1
    above would be of type B. No, it will be the type of object. because javascript classes are type of objects. but if you need to check it, you can use the `instanceof` keyword. like this, `f.b[0] instanceof B` – Vinod Liyanage Aug 24 '22 at 13:53

1 Answers1

1

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)
Vinod Liyanage
  • 945
  • 4
  • 13