petermeissner
petermeissner

Reputation: 12861

Extract elements with specific names from JSON in JavaScript

I am new to JavaScript, so please excuse my ignorance of basics and proper vocabulary.

I have a list of objects all containing specific information/variables/elements (latitde and longitude) which I would like to have in separate arrays.

 var data = [{
     "0": "44",
     "latitude": "44",
     "1": "11",
     "longitude": "11"
 }, {
     "0": "45",
     "latitude": "45",
     "1": "12",
     "longitude": "12"
 }, {
     "0": "46",
     "latitude": "46",
     "1": "13",
     "longitude": "13"
 }, {
     "0": "47",
     "latitude": "47",
     "1": "14",
     "longitude": "14"
 }];

I know already that I can access specific values easily:

data[1].latitude
data[1].longitude

But how do I put them together to get something like this? :

var latitude = [44, 45, 46, 47]
var longitude = [11, 12, 13, 14]

Upvotes: 0

Views: 75

Answers (2)

Praveen
Praveen

Reputation: 56501

Very similar to @Darin Dimitrov, but using .map() of array

Array.prototype.map() Creates a new array with the results of calling a provided function on every element in this array.

Updates: It should have been like this

var lat = data.map( function(item) {
   return item.latitude;
});

var lon = data.map( function(item) {
   return item.longitude;
});

JSFiddle

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could loop through the elements of the data array and add the desired values to other arrays that will hold the result:

var latitudes = [];
var longitudes = [];
for (var i = 0; i < data.length; i++) {
    latitudes.push(data[i].latitude);
    longitudes.push(data[i].longitude);
}

// at this stage the latitudes and longitudes arrays 
// will contain the desired values

Also in your data array, the latitudes and longitudes are strings whereas in your expected arrays you want integers. So you might need to parse the values using the parseInt function before adding them to the resulting arrays.

latitudes.push(parseInt(data[i].latitude, 10));
longitudes.push(parseInt(data[i].longitude, 10));

or with the parseFloat function if those strings could represent decimal numbers (which is more realistic for latitudes and longitudes).

Upvotes: 2

Related Questions