0

I have the following classes:

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
    }
}

And I have a JSON object such as:

[{
    "id": 1,
    "title": "response",
    "snippets": [{
        "id": 2,
        "text": "My response"
    }, {
        "id": 3,
        "text": "My other response"
    }]
}]

I'm able to create a new Term object as follows:

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

However, the snippets property does not create Snippet objects from this. What's the best way to do that?

Apollo
  • 8,874
  • 32
  • 104
  • 192
  • Add a static method to `Term`, e.g. `fromJSON`, that parses the JSON, creates `Snippets` instances and passes them to `new Term` along with the other parameters. There is no automagical way to do that. – Felix Kling Nov 14 '19 at 22:08

1 Answers1

1

You can remap your snippets using Object.assign in the array itself:

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);
Blue
  • 22,608
  • 7
  • 62
  • 92