[英]Javascript how to assign multiple nested class instances from json object
I have a json with the below format:我有一个 json 格式如下:
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 从构造函数中接收这个 json 将它变成这个 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
的格式:
class B {
construtor(json){
Object.assign(this, json)
}
}
How can I instantiate class B
from the object passed to A
so that fb[0]
and fb[1]
above would be of type B
?如何从传递给A
的 object 实例化 class B
,以便上面的fb[0]
和fb[1]
属于B
类型?
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 ab[0] instance of class B?', ab[0] instanceof B)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.