Search code examples
javascriptjqueryjson

Array to JSON array of strings


Mapping an object AppData like

heatPoints = AppData.map(function (point) {
        return [point.Latitude, point.Longitude];
});

returns

console.log(JSON.stringify(heatPoints));

                   

[[49.2898,-123.1364],[49.2752,-88.150209833],[49.2286,-123.1515]]

but I need to load them into JSON Points as an array of JSON String like:

var schoolPoints = {
                    "Points": [
                               {"latitude":49.2898,"longitude":-123.1364},
                               {"latitude":49.2752,"longitude":-123.0719},
                               {"latitude":49.2286,"longitude":-123.1515}
                      ]
                    };

How can I do this?


Solution

  • Change your map to return an object instead of an array, like so:

    heatPoints = AppData.map(function (point) {
        return {
            "latitude": point.Latitude, 
            "longitude": point.Longitude 
        };
    });
    

    Then you can additionally set it as a property to a variable in order to get the specific JSON you requested:

    heatPoints = {"Points": heatPoints};
    

    Which will result in the exact JSON that you requested.