将JSON映射到ES6类

Bar*_*ode 4 javascript json class coffeescript ecmascript-6

我有我们的员工在json文件中,并有想法使用ES6类的数据.我越用这个工作,我就越觉得我可能会遗漏一些东西.我这样做是在coffeescript中工作的:

fetch  = require('node-fetch')
domain = 'domain.com'
apiSrc = 'api.domain.com'
slug   = 'people'

class Person
  constructor: (json) -> {name: @name, title: @title, school: @school, bio: @bio} = json
  email: (username) ->
    username.replace(/\s/, '.').toLowerCase() + '@' + domain
  profile: ->
    content = []
    if this.name   then content.push("#{@name}")
    if this.title  then content.push("#{@title}")
    if this.school then content.push(school) for school in "#{@school}"
    if this.bio    then content.push("#{@bio}")
    if this.name   then content.push(this.email("#{@name}"))
    content.join('')

fetch('http://' + apiSrc + '/' + slug + '.json')
  .then((response) -> response.json())
  .then((api) ->
    content = []
    group   = []
    group.push(new Person(them)) for them in api[slug]
    for them, index in group
      content.push(them.profile())
      console.log(content.join(''))
  )
Run Code Online (Sandbox Code Playgroud)

但后来我觉得如果我能把它转换成ES6会更好.我知道用例很简单,并且类当然不是必需的,因为我只是使用数据进行模板化,但是,为了学习,我试图这样做.我是以错误的方式来做这件事的吗?现在,我觉得应该有办法让所有我投入Person课堂的"人"回归.但是,我能弄清楚如何做到这一点的唯一方法是运行for循环然后将其写入文档.

class Person {
  constructor(data) { ({name: this.name, title: this.title, school: this.school, bio: this.bio, email: email(this.name)} = data); }
  email(username) {
    return username.replace(/\s/, '.').toLowerCase() + '@' + location.hostname.replace(/[^\.\/\@]+\.[^\.\/]+$/, '');
  }
  profile() {
    return `${this.name} ${this.title}`;
  }
}

var apiSrc = 'api.domain.com';
var slug   = 'people';
fetch(`http://${apiSrc}/${slug}.json`)
  .then(function(response) { return response.json() }) // .then(response => response.json())
  .then(function(api) {
    var content = [];
    var group = [];
    for (var i = 0; i < api[slug].length; i++) { var them = api[slug][i]; new Person(them); }
    for (var i = 0; index < group.length; i++) {
      var them = group[i];
      content.push(them.profile());
      console.log(content.join(''));
    }
  });
Run Code Online (Sandbox Code Playgroud)

我的ES6转换实际上现在还没有工作.API返回JSON,但之后就搞砸了.任何建议都会非常有用,因为我正在努力让自己更好地成为一名程序员,希望这样的例子可以帮助其他人在一个真实的用例中学习类.

Joe*_*and 5

您可以尝试使用reviver参数JSON.parse.这是一个简化的例子:

class Person {
  // Destructure the JSON object into the parameters with defaults
  constructor ({name, title, school=[]}) {
    this.name = name
    this.title = title
    this.school = school
  }
}

var api = JSON.parse(a, function (k,v) {
  // Is this a new object being pushed into the top-level array?
  if (Array.isArray(this) && v.name) {
    return new Person(v)
  }
  return v
})

var group = api["people/administration"]
Run Code Online (Sandbox Code Playgroud)