I get a JSON string from an API, and I want to deserialise it in my Angular 6 website.

I don't know how dictionaries work in TypeScript. So I try to avoid them as much as I can when it should be received from an api.

When I do :

console.log(JSON.parse(viewed_availab));

I can see this result :

[{
    "2019-05-10T00:00:00": {
        "TotalStopsCount": null,
        "TotalRoutesCount": null,
        "TotalStopsCountAfterBooking": null,
        "OccupancyRate": null,
        "OccupancyRateAfterBokking": null,
        "ZoneId": null,
        "DomainName": "MTH",
        "Date": "2019-05-10T00:00:00",
        "IsAvailable": false,
        "Status": {
            "Message": "Not enough time for items to reach final destination",
            "StatusID": 1
        },
        "IdDomains": null,
        "Items": []
    },
    "2019-05-10T00:00:00": {
        "TotalStopsCount": null,
        "TotalRoutesCount": null,
        "TotalStopsCountAfterBooking": null,
        "OccupancyRate": null,
        "OccupancyRateAfterBokking": null,
        "ZoneId": null,
        "DomainName": "MTH",
        "Date": "2019-05-10T00:00:00",
        "IsAvailable": false,
        "Status": {
            "Message": "Not enough time for items to reach final destination",
            "StatusID": 1
        },
        "IdDomains": null,
        "Items": []
}]

And here is the request I execute to receive this string:

this.dataService.post('cleard.api.timeslot.viewed_availabilities', new ViewedAvailabilityParams(search.postalCode, search.userName, search.date, search.businessUnitId, search.originLocationId))
.then((viewed_availab: string) => {
...
    }).catch((error) => { this.searching = false; });

I would like the result to be in a typescript dictionary :

Dictionary<Date, Availibility> // in a typescript way.

where date represents the key (first line of the Json), and availability represents the content:

{"TotalStopsCount": null,
"TotalRoutesCount": null,
"TotalStopsCountAfterBooking": null,
"OccupancyRate": null,
... and so on }

(I already have a model done for Availability).

1 Answers

0
Mike On Best Solutions

A dictionary in Typescript/Javascript is just an Object. You can iterate through it using Object.entries:

const dictionary = {
  'key1': value1,
  'key2': value2
};

Object.entries(dictionary).forEach(([key, value]) => {
  // ...
});

Appropriate types that might be appropriate: Record<TKey, TValue>, { [key: string]: T }