Search code examples
jsonangulartypescriptnativescriptnativescript-angular

How to reshape json data into another format


so I am getting data from my API in this format:

[
    {
        "lattitude": 52.57812538272844,
        "longitude": -1.7111388218750108,
    },
    {
        "lattitude": 53.043884,
        "longitude": -2.923782,
    }
]

I need the data to look like this, so latitude has to be 'lat' and longitude has to be 'lng' etc.

[{
            lat: 52.57812538272844,
            lng: -1.7111388218750108,
        },
        {
            lat: 52.3602160,
            lng: 4.8891680,
}]

I know there is some data missing, I will fix this later. Is there any way of doing this without changing the API. I'm using Angular-nativescript with a .net backend


Solution

  • Is the data static for you? Or is it an observable?

    Assuming it is static, take advantage of the map operator on arrays. It transforms an array into a new array.

    const data = [
        {
            "lattitude": 52.57812538272844,
            "longitude": -1.7111388218750108,
        },
        {
            "lattitude": 53.043884,
            "longitude": -2.923782,
        }
    ];
    
    const dataYouWant = data.map((point: any) => ({lat: point.lattitude, lng: point.longitude }));
    

    If it is an observable, let me know, I can help you in that regard as well.