我有以下类(class):
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"
}]
}]
我可以创建一个新的 Term 对象,如下所示:
let term = Object.assign(new Term, result[0])
但是,snippets
属性不会创建Snippet
对象由此。最好的方法是什么?
最佳答案
您可以在数组本身中使用 Object.assign
重新映射片段:
let term = Object.assign(new Term, {
...result[0],
snippets: result[0].snippets.map(
snip => Object.assign(new Snippet, snip))
})
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
this.asdf = 'test'
}
}
var result = [{
"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: result[0].snippets.map(snip => Object.assign(new Snippet, snip))})
console.log(term);
关于javascript - Object.assign 嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58867193/