Behseini
Behseini

Reputation: 6328

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?

Upvotes: 1

Views: 66

Answers (2)

NtFreX
NtFreX

Reputation: 11377

The map is used to reformat the items. You can use it like the following.

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

Upvotes: 2

random_user_name
random_user_name

Reputation: 26180

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.

Upvotes: 4

Related Questions