4

I'm trying to compare json data being streamed in from websockets.

An array like this would work flawlessly:

["stream","apple","orange"]

But an array of arrays not so well:

[["stream","apple","orange"],["stream","pear","kiwi"],["stream","apple","juice"]]

Any help would be greatly appreciated. Thanks in advance!

function handler(jsonString) {

    var json = jQuery.parseJSON(jsonString);

    if (json[0] == "blah") {
       //Do something
    }

    else if (json[0] == "blah2") {
        //Do something else
    }

}

1 Answer 1

4

First reference which inner Array you want [0] from the outer, then using the same square bracket notation, reference the item in that inner Array [0][1].

if (json[0][0] == "blah") {
   //Do something
}
else if (json[0][1] == "blah2") {
    //Do something else
}

So the following examples would produce this:

json[0][0];  // "stream"
json[0][1];  // "apple"

json[1][0];  // "stream"
json[1][1];  // "pear"

// etc...

To iterate over all the items in the Arrays, you'd need a loop inside a loop. The outer one to iterate through the Arrays stored in the outer Array, and the inner loop to iterate through the values of those inner Arrays.

Like this:

for( var i = 0, len_i = json.length; i < len_i; i++ ) {
    for( var j = 0, len_j = json[ i ].length; j < len_j; j++ ) {
        // do something with json[ i ][ j ]; (the value in the inner Array)
    }
}

or if you wanted jQuery.each()(docs):

jQuery.each( json, function(i,val) {
    jQuery.each( val, function(j,val_j) {
        // do something with val_j (the value in the inner Array)
    });
});

I'd prefer the for loops though.

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

3 Comments

I'm trying to find the best way to iterate through the array of arrays and tie each in to a variable that I can use to replace data on the page. Should I use $.each for this type of function? else if (json[0][0] == "stream") { //Do something else for (var i = 0; i < json.length; i++) { var stream = json[i]; var fruit1 = stream[1]; var fruit2 = stream[2]; alert(fruit1); } }
@DrEval: You'd need to do a loop inside of a loop. Yes you can use $.each, or just a simple for loop. Although I'm not certain why you would want a bunch of variables. The Array storage mechanism is designed to prevent the need for multiple variables. Is it for all the values? Or just certain ones? I'll give an example of looping in a minute.
@DrEval use a for loop to iterate the array, unless you have a specific need, performance is better.

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.