javascript - ES6/TS/Angular2 将 JSON 解析为 Date

标签 javascript json angular typescript ecmascript-6

我有以下 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 不符合我的愿望,它使用类型继承执行复制而不是深层复制。

最佳答案

我会使用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 = [];
        }
    }
}

( code in playground )

<小时/>

编辑

如果数据有更多字段,您可以使用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));
    }
}

( code in playground )

关于javascript - ES6/TS/Angular2 将 JSON 解析为 Date,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42997799/

相关文章:

Angular 订阅。无法获取数据

javascript - React Native 和 React 有什么区别?

javascript - 当子组件尝试调用传递的函数时,React 中出现 typeError 提示 this.props 不是函数

javascript - 选出一个号码

c# - 将 json 文件保存到文本文件中

ios - 将对象数组转换为数组对象

javascript - 面对超过 2000 个项目时,Dynatree 返回错误

android - 在 Android 上运行时,Ionic-Native PhotoLibrary 在 SaveImage 上崩溃

javascript - Angular2/4 在请求后填充表单

JavaScript 'SUPER' 嘶嘶声