DrEval
DrEval

Reputation: 41

How to Select from an array of arrays

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
    }

}

Upvotes: 4

Views: 9174

Answers (1)

user113716
user113716

Reputation: 322462

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.

Upvotes: 4

Related Questions