1

Is there any way to map object received from server as a JSON to class instance in CoffeeScript?

I have a lot of cases where my JSON is:

{
  id:   '123'
  name: 'wojtek'
  age:  24
}

and my coffee class is:

class Person
    constructor: (id, name, age) ->

How to directly map JSON to class instance without assigning each property separately?

1 Answer 1

1

I would suggest rewriting your constructor to accept a single object, e.g.:

class Person
  constructor: (@props) ->

or

class Person
  constructor: ({@id, @name, @age}) ->

After that you'll be able to map your JSON to class instance simply by passing it to the constructor:

person = new Person data
Sign up to request clarification or add additional context in comments.

1 Comment

OMG, that's.. awesome!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.