0

Couldn't think of better title. Important to note: I'm new to js and I guess its the reason I can't figure it out by myself.

I have a JSON array returned from a database, the JSON array represent a set of points. Example of the JSON array:

var JSON_array = [{lat:1,lng:2}, {lat:1,lng:3},{lat:2,lng:3}...]

I want to make a different array whose elements will be a function and the variables of the function will be the elements from the JSON array, like so:

var coordinates = [
new google.maps.LatLng(1, 2),
new google.maps.LatLng(1, 3),
new google.maps.LatLng(2, 3),
....
];

I made a function using forEach that counts the elements of the JSON array (for learning and trying to find a way to what I want) but I cant think of a way make the array mentioned above.

2
  • 1
    you can use map function Commented Dec 17, 2014 at 10:46
  • 2
    That example is not a JSON array. That is just simply an array. When your JSON parser is done parsing JSON, it is just an array. Commented Dec 17, 2014 at 10:57

4 Answers 4

3

You could use Array map method:

var coordinates = JSON_array.map(function(coordinate) {
    return new google.maps.LatLng(coordinate.lat, coordinate.lng);
})

This method gives you an new array based on (1) the original array and (2) how you deal with each element. Here's more detailed doc for the method.

Sign up to request clarification or add additional context in comments.

1 Comment

Clearly the best answer. Array.prototype.map() is available for all modern browsers, including IE9. kangax.github.io/compat-table/es5
3

you can also use regular for loop

coordinates = [];
for(var i=0;i<JSON_array.length;i++){
    coordinates.push(new google.maps.LatLng(JSON_array[i].lat,JSON_array[i].lng));
}

1 Comment

straightforward way :-)
2

For mapping element from one array to another you can use Array.prototype.map function like

var JSON_array = [{lat:1,lng:2}, {lat:1,lng:3},{lat:2,lng:3}...];
var coordinates = JSON_array.map(function(el){ return new google.maps.LatLng(el.lat, el.lng)});

Comments

1

As Grundy commented you can just do:

coordinates = JSON_array.map(function(x) {
                                 return new google.maps.LatLng(x.lat, x.lng);
                             });

You might want to get your nomenclature straight though, this has nothing to do with JSON.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.