1

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?

3
  • 2
    There's no such thing as a "JSON object", and there's no JSON in your question. Commented Aug 24, 2022 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? Commented Aug 24, 2022 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 Commented Aug 24, 2022 at 13:53

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.