Good day, experts! A multidimensional array in JSON (ajax) comes from the server. I bring it to the console, it looks like this:

[[["Овечка12"],["Овечка13"],["Овечка14"]],[["Овечка15"],["Овечка16"],["Овечка17"]],[["Овечка18"],["Овечка19"],["Овечка20"]],[["Овечка21"]]] 

How to get to his items? Tried like this:

  data[0][0][i] data[0][1][i] data[0][2][i] data[0][3][i] 

I tried to sort through the loop, but without success. Direct, please, on the true path, amateur ...

    3 answers 3

     var jsonObj = [[["Овечка12"],["Овечка13"],["Овечка14"]],[["Овечка15"],["Овечка16"],["Овечка17"]],[["Овечка18"],["Овечка19"],["Овечка20"]],[["Овечка21"]]]; for (var i=0;i<jsonObj.length;i++){ for (sheep in jsonObj[i]){ alert(jsonObj[i][sheep]); } } 
    • It would be better if you, with PHP, give Content-Type:application/json , so as not to do JSON.parse (response) - Roman Kozin

    JSON is, in fact, not an object. This is the string in which the object is encrypted. This line needs to be decrypted and then it will become a Javascript object. For unpacking, use the JSON.parse() method.
    Try this.

     var json = '[[["Овечка12"],["Овечка13"],["Овечка14"]],[["Овечка15"],["Овечка16"],["Овечка17"]],[["Овечка18"],["Овечка19"],["Овечка20"]],[["Овечка21"]]]'; var data = JSON.parse(json); console.log(data); console.log(data[0][0][0]); 

      The result will be a one-dimensional array through it easier to get to the elements and do with them what you want.

       var json = '[[["Овечка12"],["Овечка13"],["Овечка14"]],[["Овечка15"],["Овечка16"],["Овечка17"]],[["Овечка18"],["Овечка19"],["Овечка20"]],[["Овечка21"]]]'; var data = JSON.parse(json); function parseArray(arr) { var newArr = []; for (var i = 0; i < arr.length; i++) { if (!Array.isArray(arr[i])) { newArr.push(arr[i]); } if (Array.isArray(arr[i])) { newArr = newArr.concat(parseArray(arr[i])); } } return newArr; } console.log( parseArray(data) ); 

      • Sorry, I'm generally weak in javascripte. I send 4 arrays from the server in one array. Please tell me how to parse so that these four arrays are in different variables, you just need to display them in different parts of the page. Thank. - overtheman September