简体   繁体   English

CoffeeScript将对象映射到类实例

[英]CoffeeScript map object to class instance

Is there any way to map object received from server as a JSON to class instance in CoffeeScript? 有什么方法可以将以JSON形式从服务器接收的对象映射到CoffeeScript中的类实例?

I have a lot of cases where my JSON is: 在很多情况下,我的JSON是:

{
  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? 如何直接将JSON映射到类实例而无需分别分配每个属性?

I would suggest rewriting your constructor to accept a single object, eg: 我建议重写您的构造函数以接受单个对象,例如:

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: 之后,您只需将JSON传递给构造函数即可将JSON映射到类实例:

person = new Person data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM