0

The array keys are going to be dynamic but there are only two array items. For example the key start_location.A has a value of London and the key start_location.F has a value of Manchester

I can get the values like this

var start_location_A = result.routes[0].legs[c].steps[b].start_location.A; 
var start_location_F = result.routes[0].legs[c].steps[b].start_location.F; 

But the A and F will be dynamic, meaning the letters will be changing. How do i get the first & second items in the start_location array regardless of key name? I attempted below but says start_location.index is not a function.

var start_location_A = result.routes[0].legs[c].steps[b].start_location;
                    start_location_A = start_location_A.index(0);

                    var start_location_F = result.routes[0].legs[c].steps[b].start_location;
                    start_location_F = start_location_F.index(1);

How do i solve?

user892134
  • 2,906
  • 13
  • 50
  • 101
  • What about pushing the values of `start_location` into an array, sorted alphabetically (by keys—see tip here: http://stackoverflow.com/questions/5467129/sort-javascript-object-by-key), and then accessing the array by index? – Terry Jul 31 '15 at 12:19
  • possible duplicate of [How do I access properties of a javascript object if I don't know the names?](http://stackoverflow.com/questions/675231/how-do-i-access-properties-of-a-javascript-object-if-i-dont-know-the-names) – blgt Jul 31 '15 at 12:25

2 Answers2

2

you can iterate over the keys of the json structure: try this:

var arr=[];
var json = result.routes[0].legs[c].steps[b].start_location;
for(var o in json){
     arr.push(json[o]);
}
var start_location_A = arr[0];
var start_location_B = arr[1];

it should give you an idea

Manish Mishra
  • 11,383
  • 5
  • 23
  • 52
0

If you use a named index, when accessing an array, JavaScript will redefine the array to a standard object.

var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length;         // person.length will return 0
var y = person[0];             // person[0] will return undefined

One thing you can do is to iterate over object properties using for in loop as @Manish Misra suggested. However it is not guarenteed that you will get the objects in correct order. More Info

Community
  • 1
  • 1
Özgür Kaplan
  • 1,966
  • 2
  • 14
  • 26