Reputation: 2342
I have following json:
let JSON_RESPONSE = `{"birthDates": ["2017-01-02","2016-07-15"]}`
I have a TypeScript
object with Date
array declared and a ES6
featured constructor init:
class Children {
birthDates: Date[] = []
constructor(values: Object = {}) {
Object.assign(this, values)
}
}
I want to init this object from JSON output it's days:
const children = new Children(JSON.parse(this.JSON_RESPONSE))
children.birthDates.forEach(it => {
console.log(it.getDate())
})
Obviously it doesn't work because Children#birthDates
are of Object
type instead of Date
. And adding explicit new Date()
initialization helps:
children.birthDates.forEach(it => {
console.log(new Date(it).getDate())
})
The question is how to painlessly convert JSON to legit Date
objects on object's constructor stage without manually mapping every property to the JSON input.
Clearly, Object.assign
doesn't fit my desires and performs shallow
copy instead of deep
with type inheritance.
Upvotes: 0
Views: 103
Reputation: 164447
I'd use Array.prototype.map in the constructor to get all values as dates:
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 = [];
}
}
}
In the case where the data has more fields you can use Object.assign
and then override the birthDates
property with the mapped version:
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));
}
}
Upvotes: 1