0

I need to access JavaScript objects stored in a multi-dimensional array. The data is being exported by a WordPress plug-in. Note, I cannot change the code to use a single array.

There are two arrays named "employees". Is this array format compatible with JavaScript? The JSON export was intended for PHP processing.

(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:

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


How for example, would one access the value "Peter0" in the first array? 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.

nibl
  • 13
  • 4
  • It's the semicolon at the end of the JSON string that makes this code not work. Remove it and it will work, your property access is correct – Kaddath Mar 08 '18 at 12:49
  • The additional semicolon within the JSON was just a typo. It does not change access to the array. I still cannot access the first array. – nibl Mar 08 '18 at 13:02

1 Answers1

2

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

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • Thanks, that was my suspicion. Do you have any suggestions how to process the existing JSON so that I can access all key/value pairs? – nibl Mar 08 '18 at 13:06
  • An object cannot have two properties of same name, you need to change the name of one of those two properties. – gurvinder372 Mar 08 '18 at 13:07
  • @nibl the JSON you get is a bit strange, it's the same in PHP as in Javascript, an associative array cannot have twice the same key without the newest overriding the first. There must be something wrong with the plugin generating it – Kaddath Mar 08 '18 at 13:09
  • Thanks, I will pass this on to the plug-in developer. Do you know whether this is JavaScript specific? He said this format is okay for PHP processing. – nibl Mar 08 '18 at 13:10
  • @Kaddath Thanks, I will pass this on to the developer. – nibl Mar 08 '18 at 13:19