0

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...

Brian Powell
  • 3,336
  • 4
  • 34
  • 60

3 Answers3

2

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.

Community
  • 1
  • 1
ecyshor
  • 1,319
  • 1
  • 10
  • 15
1
jsonOutput.red[0]

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

Brad
  • 159,648
  • 54
  • 349
  • 530
1

You access those arrays using:

jsonOutput.red;
jsonOutput.orange;
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • The thing is though, I need to be able store whatever the name IS into a variable so that I can compare it against values from another array, (to see if `var1` contains items that `var2` doesn't. I need to know how to access that... `location`, for lack of a better word, rather than the actual name directly (e.g. `red`, `orange`), which is why I was trying to use `[0]` – Brian Powell Mar 30 '15 at 14:40
  • 1
    @JohnWu you can use `for (var key in jsonOutput) {` – jcubic Mar 30 '15 at 14:47
  • hah. I JUST got to that part in the thread linked by @Nicu Reut, and it works perfectly. Thank you :) – Brian Powell Mar 30 '15 at 14:47