简体   繁体   中英

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.

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.

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' },
];

define it like:

let locations = [
    { location_id: 1, location_name: 'Main office'},
    { location_id: 2, location_name: 'any name' },
];

locations.forEach(location => {
    alert(location.location_id);
});

Or if your data is in json format:

let json = '{ "locations": [ { "location_id": 3, "location_name": "Name" } ]}';

const data = JSON.parse(json);

data.locations.forEach(location => {
    console.log(location.location_id);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM