Sometimes you have to handle some type of array (JSONArray, int Array, etc) at client side, i.e. in jsp or html file. And you want to iterate this array in JavaScript. How is this possible?
I’ve created simple complete solution with an example. Below example will get JSONArray as an input and we will iterate through it and will create HTML table to make sure it’s working.
Input:
Output:
<HTML> <HEAD> <TITLE>Crunchify - Iterate through JSONArray in JavaScript</TITLE> <style type="text/css"> body { background-image: url('https://crunchify.com/wp-content/uploads/2013/03/Crunchify.bg_.300.png'); } </style> <script> var graph = { "sparkData" : [ { "one" : [ 97, 5, 69, 35, 28, 52, 51, 55 ] }, { "two" : [ 96, 63, 18, 55, 13, 47, 77, 64 ] }, { "three" : [ 94, 75, 83, 44, 43, 86, 68, 26 ] } ] } var i = 0 document.writeln("<br><br><div align='center'><table border='1'><tr>"); for ( var i = 0; i < graph.sparkData.length; i++) { var obj = graph.sparkData[i]; console.log(obj); var crunchifyName; var crunchifyValue; document.writeln("<td>"); document.writeln("<table border='0' width=100 >"); for ( var key in obj) { crunchifyName = key; crunchifyValue = obj[key].toString(); +document.writeln("<tr><td><B>" + crunchifyName + ": </B></td><td width=50>" + crunchifyValue + "</td></tr>"); document.writeln("</table>"); document.writeln("</td>"); } } document.writeln("</tr></table></div>"); </script> </HEAD> <BODY> <br> <br> <br> <div align="center"> <div style="font-family: verdana; line-height: 25px; padding: 5px 10px; border-radius: 10px; border: 3px solid #EE872A; width: 50%; font-size: 12px;"> Crunchify - Iterate through JSONArray in JavaScript by <a href='https://crunchify.com'>Crunchify</a>. Click <a href='https://crunchify.com/category/java-tutorials/'>here</a> for all Java, Spring MVC, Web Development examples.<br> </div> </div> </BODY> </HTML>
Example2: (you can put below code to above .html file to see console result)
Input Data:
var dictionary = { "employee1":[ {"id":"0","name":"Google"}, {"id":"1","name":"eBay"} ], "employee2": [ {"id":"2","name":"Yahoo"}, {"id":"3","name":"Facebook"} ] };
Javascript code to iterate above JSON element:
var employee1 = dictionary.employee1; var employee2 = dictionary.employee2; for ( var i in employee1) { var id = employee1[i].id; var name = employee1[i].name; console.log(id); console.log(name); } for ( var i in employee2) { var id = employee2[i].id; var name = employee2[i].name; console.log(id); console.log(name); }
Result from console log (I use Google Chrome):