Object.assign嵌套属性

时间:2019-11-14 22:02:27

标签: javascript json

我有以下课程:

@post("/api")
def API():
    payload = merge_dicts(dict(request.forms), dict(request.query.decode()))
    print(payload)

我有一个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
    }
}

我能够创建一个新的Term对象,如下所示:

[{
    "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对象。最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以在数组本身中使用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);