-2

I got this type of json format after a get request:

{
"name" : "cow",
"date" : {
    "year" : 2012,
    "month" : "JANUARY",
    "dayOfMonth" : 1,
    "dayOfWeek" : "FRIDAY",
    "dayOfYear" : 1,
    "monthValue" : 1,
    "hour" : 2,
    "minute" : 2,
    "second" : 0,
    "nano" : 0,
    "chronology" : {
      "id" : "ISO",
      "calendarType" : "iso8601"
    }
  }
....
}

How can I convert the above to the following in typescript/angular:

{
"name" : "cow",
"date" : "2012-01-01"
}

Then store in the below array.

//....correctFormat = [];
service.convertStore()
  .subscribe((data: any) => {
    // manipulation here

    correctFormat = "holds result"
})
Pleasure
  • 279
  • 2
  • 6
  • 19
  • Does this answer your question? [javascript create date from year, month, day](https://stackoverflow.com/questions/40981982/javascript-create-date-from-year-month-day), then [How to format a JavaScript date](https://stackoverflow.com/q/3552461/215552) – Heretic Monkey Jan 23 '20 at 19:26

2 Answers2

0

You can create a class in Angular:

export class MyCustomClass {
   name: string;
   date: string;

   constructor(name: string, date: string) {
       this.name = name;
       this.date = string;
   }
}

Then in the service invocation should do:

service.convertStore()
  .subscribe((data: any) => {
    // manipulation here
    const newFormat = new MyCustomClass(data['name'], `${data['date']['year']}-${data['date']['monthValue']}-${data['date']['dayOfMonth']}`
    correctFormat = "holds result"
})
German Quinteros
  • 1,870
  • 9
  • 33
0

Access to each member, assign it to a new object and store it in the array:

const object = {
  "name": "cow",
  "date": {
    "year": 2012,
    "month": "JANUARY",
    "dayOfMonth": 1,
    "dayOfWeek": "FRIDAY",
    "dayOfYear": 1,
    "monthValue": 1,
    "hour": 2,
    "minute": 2,
    "second": 0,
    "nano": 0,
    "chronology": {
      "id": "ISO",
      "calendarType": "iso8601"
    }
  }
}

const d = object.date
correctFormat = [];
correctFormat.push({
  name: object.name,
  date: d.year + '-' + (0 + '' + d.monthValue).slice(-2) + '-' + (0 + '' + d.dayOfMonth).slice(-2)
});

console.log(correctFormat)
Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110