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.

2
  • 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 Commented Mar 8, 2018 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. Commented Mar 8, 2018 at 13:02

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

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?
An object cannot have two properties of same name, you need to change the name of one of those two properties.
@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
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.
@Kaddath Thanks, I will pass this on to the developer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.