How to select an array of arrays

I am trying to compare json data passed from websockets.

Such an array will work flawlessly:

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

But an array of arrays is not very good:

[["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
    }

}
+3
source share
1 answer

First, indicate in which internal array you want [0]from the external, then using the same square notation, refer to the element in this internal array [0][1].

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

So, the following examples will lead to the following:

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

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

// etc...

To iterate over all the elements in arrays, you need a loop inside the loop. External for iterating through arrays stored in an external array, and an internal loop for iterating over the values ​​of these internal 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 want 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 would prefer loops for.

+3
source

Source: https://habr.com/ru/post/1787226/


All Articles