简体   繁体   English

如何在JavaScript中访问对象的多维数组?

[英]How do you access multi-dimensional arrays of objects in JavaScript?

I need to access JavaScript objects stored in a multi-dimensional array. 我需要访问存储在多维数组中的JavaScript对象。 The data is being exported by a WordPress plug-in. 数据正在通过WordPress插件导出。 Note, I cannot change the code to use a single array. 注意,我不能更改代码以使用单个数组。

There are two arrays named "employees". 有两个名为“员工”的数组。 Is this array format compatible with JavaScript? 这种数组格式与JavaScript兼容吗? The JSON export was intended for PHP processing. JSON导出用于PHP处理。

(Note, The code below is a simplified model to illustrate the issue). (注意,下面的代码是一个简化的模型来说明问题)。

var data = '{"employees":[{"firstName":"John0"},  {"firstName":"Anna0"},{"firstName":"Peter0"}],"employees":[{"firstName":"John1"},  {"firstName":"Anna1"},{"firstName":"Peter1"}]};';

var json = JSON.parse(data);

document.querySelector('#test').innerHTML = json.employees[2].firstName;

Here it is on JSFiddle: 它在JSFiddle上:

https://jsfiddle.net/2524fhf4/11/ https://jsfiddle.net/2524fhf4/11/


How for example, would one access the value "Peter0" in the first array? 例如,如何在第一个数组中访问值“ Peter0”? In a single array, it would be accessed like this: 在单个数组中,将这样访问它:

var result = json.employees[2].firstName;

It appears to me that in this format it is only possible to access the last array. 在我看来,以这种格式只能访问最后一个数组。

It appears to me that in this format it is only possible to access the last array. 在我看来,以这种格式只能访问最后一个数组。

Because when your object literal has two (or more) keys of the same name , last one will override the rest of them . 因为当您的对象文字具有两个(或多个)相同名称的键时最后一个 将覆盖其余

Check this demo 检查这个演示

 var data = '{"employees":[{"firstName":"John0"}, {"firstName":"Anna0"},{"firstName":"Peter0"}],"employees":[{"firstName":"John1"}, {"firstName":"Anna1"},{"firstName":"Peter1"}]}'; console.log(JSON.parse(data)); //it will only display first one 

In the above example, you can see that there is only one key of the data 在上面的示例中,您可以看到data只有一个键

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

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