fasth
fasth

Reputation: 2342

ES6/TS/Angular2 parsing JSON to Date

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

Answers (1)

Nitzan Tomer
Nitzan Tomer

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 = [];
        }
    }
}

(code in playground)


Edit

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));
    }
}

(code in playground)

Upvotes: 1

Related Questions