javascript - Object.assign 嵌套属性

标签 javascript json

我有以下类(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/

相关文章:

javascript - 如果 es6 变量对象为空,如何显示嵌入条件

php - 如何获取与以下 JSON 对象的距离值?

Python - 从 JSON 创建字典时遇到问题

php - html中元素的可见性属性或显示属性哪个更好?

Python 从带有 boto3 错误的代码调用我的 AWS lambda

c# - 服务器未返回状态代码为 400 的 JSON (.net)

python - 'dict' 对象没有属性 'append' Json

javascript - 简单正则表达式的问题

javascript - 如何检测字符串中的单位?

JavaScript 函数、数组和对象