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?

2

2 Answers 2

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

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.