Brian Powell
Brian Powell

Reputation: 3411

How do I access these elements of this JSON-encoded javascript?

I have an array in PHP that I encode to json:

$jsonOutput = json_encode($output);

Then in my javascript, I use this to parse it:

var jsonOutput    = JSON.parse('<?php echo $jsonOutput; ?>');

My output looks like this in the Chrome console:

enter image description here

Ultimately, I have two arrays, and I'm trying to write a compare between the two to show if there are any items in the first array that aren't in the second, but I'm not sure how to reference red and orange here.

I tried console.log(jsonOutput[0]) but I get undefined.

Also, as a side note, does anyone have any good resources for reading up on arrays in javascript and all their ins-and-outs? It seems to be one aspect that I'm struggling with lately...

Upvotes: 0

Views: 48

Answers (3)

ecyshor
ecyshor

Reputation: 1439

The problem is that your jsonOutput is an Object, so in order to access one member of the object you either have to user jsonOutput.red/jsonOutput.orange or jsonOutput["red"], jsonOutput["orange"] to access a member of the object.

More info here Access / process (nested) objects, arrays or JSON.

Upvotes: 2

jcubic
jcubic

Reputation: 66590

You access those arrays using:

jsonOutput.red;
jsonOutput.orange;

Upvotes: 1

Brad
Brad

Reputation: 163458

jsonOutput.red[0]

You have an object with two keys. Not an array.

Upvotes: 1

Related Questions