Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – Error when accessing an associative array value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

  1. "locations" array seems to be a part of another object
  2. All elements of "locations" array are of type String hence the locations[i].location_id would not work as the "dot" operator expects an object

Suggestions

  1. 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' },
];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading