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?

1
  • 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. Commented Nov 14, 2019 at 22:08

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.