简体   繁体   English

Javascript - 访问关联数组值时出错

[英]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.我试图遍历此数组以显示位置 ID/名称,但不断收到未定义的错误。

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.如果我执行alert(locations[i]) ,我可以看到该索引的各个数组内容,但似乎无法进一步查看 go 。

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.我读过的所有内容都表明我应该能够通过使用 for [i] 循环来获取数组的值。

I will list all the noticeable problems in your query我将列出您查询中所有明显的问题

  1. "locations" array seems to be a part of another object “位置”数组似乎是另一个 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 “locations”数组的所有元素都是String类型,因此locations[i].location_id将不起作用,因为“点”运算符期望 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:或者,如果您的数据是 json 格式:

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

const data = JSON.parse(json);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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