Tom
Tom

Reputation: 721

JavaScript - access array

I'm currently looping through an array of waypoints that are returned from the Google Maps API, in the following array I wish to access the values that are labelled Xa and Ya and at the moment I am doing it in this way - [i]["location"]["Xa"], however Xa and Ya are not always the same, sometimes it could be aB and aC or Ya and Za etc. Is there a generic way to access these values?

[
   {
      "location":{
         "Xa":xx.xxxxxxxxxxxxx,
         "Ya":xx.xxxxxxxxxxxxx
      },
      "stopover":true
   },
   {
      "location":{
         "Xa":xx.xxxxxxxxxxxxx,
         "Ya":xx.xxxxxxxxxxxxx
      },
      "stopover":true
   },
   {
      "location":{
         "Xa":xx.xxxxxxxxxxxxx,
         "Ya":xx.xxxxxxxxxxxxx
      },
      "stopover":true
   },
   {
      "location":{
         "Xa":xx.xxxxxxxxxxxxx,
         "Ya":xx.xxxxxxxxxxxxx
      },
      "stopover":true
   }
]

Upvotes: 0

Views: 6065

Answers (4)

Gautham Badhrinathan
Gautham Badhrinathan

Reputation: 2437

First of all, this is a javascript object (All associative arrays are actually objects in JavaScript).

If you are sure that the location object will contain only 2 properties, you can use the for ... in statement and be sure that the first element you access is the X Coordinate and the 2nd is the Y Coordinate.

Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Upvotes: 1

Marcelo
Marcelo

Reputation: 9407

First of all, as Gautham Badhrinathan pointed out, there are no associative arrays in javascript. Instead they are objects. (your sample code is JSON and JSON stands for JavaScript Object Notation).

Secondly, .Xa and .Ya are minified names for the .lat() and .lng() methods, so you should not use them because they can change with the next version release.

Third, location is already a google.maps.LatLng() object, so you can use it directly, as in:

for(var i = 0 ; i < yourArray.length ; i++){
    setMarker(yourArray[i].location);

}

function setMarker(latLng){
    var marker = new google.maps.Marker({
        map: map,
        position: latLng
    })
}

Finally, if you really need to read the individual values you should use the documented methods, such as:

for(var i = 0 ; i < yourArray.length ; i++){
    var lat = yourArray[i].location.lat();
    var lng = yourArray[i].location.lng();

// do something with vars lat and lng
}

Upvotes: 1

Jill-J&#234;nn Vie
Jill-J&#234;nn Vie

Reputation: 1841

You can do it this way:

for(key in tab[i]["location"]) {
    if(tab[i]["location"].hasOwnProperty(key)) {
        console.log(tab[i]["location"][key]);
    }
}

Upvotes: 0

Hunter McMillen
Hunter McMillen

Reputation: 61540

You can test to see if certain properties exist in your objects before trying to extract them using the hasOwnProperty() method

example: http://jsfiddle.net/Fd6Ex/6/

Upvotes: 0

Related Questions