ES6/TS/Angular2 解析 JSON 到目前为止



>我有以下json:

let JSON_RESPONSE = `{"birthDates": ["2017-01-02","2016-07-15"]}`

我有一个TypeScript对象,其中声明了Date数组和一个ES6特色构造函数 init:

class Children {
birthDates: Date[] = []
constructor(values: Object = {}) {
Object.assign(this, values)
}
}

我想从 JSON 输出中初始化这个对象,这是几天:

const children = new Children(JSON.parse(this.JSON_RESPONSE))
children.birthDates.forEach(it => {
console.log(it.getDate())
})

显然它不起作用,因为Children#birthDatesObject类型而不是Date.添加显式new Date()初始化有助于:

children.birthDates.forEach(it => {
console.log(new Date(it).getDate())
})

问题是如何在对象的构造函数阶段轻松地将 JSON 转换为合法的Date对象,而无需手动将每个属性映射到 JSON 输入。

显然,Object.assign不符合我的愿望,并且执行shallow复制而不是使用类型继承deep

我会在构造函数中使用 Array.prototype.map 将所有值作为日期获取:

type Data = {
birthDates: string[];
}
class Children {
birthDates: Date[];
constructor(values?: Data) {
if (values) {
this.birthDates = values.birthDates.map(value => new Date(value));
} else {
this.birthDates = [];
}
}
}

(操场上的代码)


编辑

如果数据具有更多字段,则可以使用Object.assign,然后使用映射版本覆盖birthDates属性:

interface IChildren {
size: number;
groudId: string;
birthDates: string[];
}
class Children {
size: number = 0;
groudId: string = null;
birthDates: Date[] = [];
constructor(values?: IChildren) {
if (values) {
Object.assign(this, values);
}
this.birthDates = this.birthDates.map(value => new Date(value));
}
}

(操场上的代码)

相关内容

最新更新