Javascript Object.assign嵌套属性

Javascript Object.assign嵌套属性,javascript,json,Javascript,Json,我有以下课程: class Term { constructor(id, title, snippets){ this.id = id this.title = title this.snippets = snippets } } class Snippet { constructor(id, text) { this.id = id this.text = text } } 我有

我有以下课程:

class Term {
    constructor(id, title, snippets){
        this.id = id
        this.title = title
        this.snippets = snippets
    }
}

class Snippet {
    constructor(id, text) {
        this.id = id
        this.text = text
    }
}
我有一个JSON对象,比如:

[{
    "id": 1,
    "title": "response",
    "snippets": [{
        "id": 2,
        "text": "My response"
    }, {
        "id": 3,
        "text": "My other response"
    }]
}]
我可以创建一个新的术语对象,如下所示:

let term = Object.assign(new Term, result[0])

但是,
snippets
属性不会从此创建
Snippet
对象。最好的方法是什么?

您可以使用
对象重新映射代码段。在数组本身中分配

let term = Object.assign(new Term, {
    ...result[0],
    snippets: result[0].snippets.map(
        snip => Object.assign(new Snippet, snip))
})
类术语{
构造函数(id、标题、代码段){
this.id=id
this.title=标题
this.snippets=代码段
}
}
类片段{
构造函数(id,文本){
this.id=id
this.text=文本
this.asdf='test'
}
}
var结果=[{
“id”:1,
“标题”:“回复”,
“片段”:[{
“id”:2,
“文本”:“我的回应”
}, {
“id”:3,
“文本”:“我的其他回应”
}]
}]
让term=Object.assign(新的term,{…结果[0],代码段:结果[0]。snippets.map(snip=>Object.assign(新代码段,snip))})

控制台日志(术语)
术语
添加一个静态方法,例如
fromJSON
,该方法解析JSON,创建
片段
实例,并将它们与其他参数一起传递给
新术语
。没有自动的方法可以做到这一点。谢谢!完美地工作