Advertisements
I have an array, locations:
{
"locations":[
"{\"location_id\":\"1\",\"location_name\":\"Main Office\"}",
"{\"location_id\":\"6\",\"location_name\":\"Secondary\"}"
]
}
I am trying to loop through this array to display the location id/name, but keep getting undefined errors.
for (var i = 0; i < locations.length; ++i) {
alert(locations[i].location_id);
}
If I do alert(locations[i])
, I can see the individual array contents for that index, but seemingly have no way go any further.
I feel like I’m missing something incredibly simple and would appreciate any help. Everything I’ve read suggests I should just be able to get the value of the array by using the for [i] loop.
>Solution :
I will list all the noticeable problems in your query
- "locations" array seems to be a part of another object
- All elements of "locations" array are of type
String
hence thelocations[i].location_id
would not work as the "dot" operator expects an object
Suggestions
- Make sure "locations" is an array of objects which is properly formatted for eg:
let locations = [
{ location_id: 1, location_name: 'Main office'},
{ location_id: 2, location_name: 'any name' },
];