JSON到Javascript类 [英] JSON to Javascript Class

查看:90
本文介绍了JSON到Javascript类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个http请求,该请求从nosql数据库获取此Json对象:

I have a http request that gets this Json object from a nosql database:

let jsonBody = {
    birthday : 1997,
    firstname: 'foo',
    lastname:'bar'
}

然后我要将这些信息加载到Student模型中:

Then I want to load this information into the Student model:

class Student{
    constructor(){

    }

    getFullname(){
        return this.lastname+' '+this.firstname
    }
    getApproxAge(){
        return 2018- this.birthday
    }
}

通常,我会将此方法添加到此类:

Normally, I would add this method to this class:

fromJson(json){
    this.studentId = json.studentId;
    this.birthday = json.birthday;
    this.firstname = json.firstname;
    this.lastname = json.lastname;
}

我将按以下方式使用它:

I would use it as follow:

let student = new Student()
student.fromJson(jsonBody)
console.log(student.getFullname())
console.log(student.getApproxAge())

这很好,但我的问题是我有:现实中有100个专有权.我需要用fromJson方法一一写所有属性吗?

This works fine but my problem is I have: 100 proprieties in reality. Will I have to write all proprities one by one in the fromJson method?

而且,如果专有名称发生了变化,那么说:姓氏变成了姓氏,我将不得不对其进行修复?

And also, if a propriety name has change, let's say: lastname became LastName, I will have to fix it?

是否有一种简单的方法将这些值动态分配给对象Student,但保留其所有方法?

Is there a simpler way to just assign these values to the object student dynamically but keep all of its methods??

类似这样的东西:

fromJson(json){
    this = Object.assign(this, json) //THIS IS NOT WORKING
}

推荐答案

只需分配给一个实例:

 static from(json){
   return Object.assign(new Student(), json);
 }

因此您可以这样做:

 const student = Student.from({ name: "whatever" });


或将其设为实例方法并忽略分配对象:


Or make it an instance method and leave away the assignemnt:

 applyData(json) {
   Object.assign(this, json);
 }

因此您可以:

 const student = new Student;
 student.applyData({ name: "whatever" });

它也可以是构造函数的一部分:

It could also be part of the constructor:

 constructor(options = {}) {
  Object.assign(this, options);
 }

那么你可以做:

 const student = new Student({ name: "whatever" });

而且,如果属性名称已更改,则说:姓氏变为姓氏,我将不得不对其进行修复?

And also, if a property name has changed, let's say: lastname became LastName, I will have to fix it?

是的,您将不得不修复它.

Yes you will have to fix that.

这篇关于JSON到Javascript类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆