我有以下 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#birthDates
是 Object
类型而不是 Date
。添加显式 new Date()
初始化有助于:
children.birthDates.forEach(it => {
console.log(new Date(it).getDate())
})
问题是如何在对象的构造函数阶段轻松地将 JSON 转换为合法的 Date
对象,而无需手动将每个属性映射到 JSON 输入。
显然,Object.assign
不符合我的愿望,它使用类型继承执行浅
复制而不是深层
复制。
最佳答案
我会使用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));
}
}
关于javascript - ES6/TS/Angular2 将 JSON 解析为 Date,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42997799/