Nested Arrays in JSON Objects
JSON arrays are written inside square brackets.
Just like in JavaScript, an array can contain objects:
Values in an array can also be another array, or even another JSON object:
Example(1)
var myObj, i, j, x = ""; myObj = { "name":"Shiva", "age":30, "cars": [ {"name":"Ford", "models":["Fiesta", "Focus", "Mustang"]}, {"name":"BMW", "models":["320", "X3", "X5"]}, {"name":"Fiat", "models":["500", "Panda"] } ] }
for (i in myObj.cars) { x += "<h2>" + myObj.cars[i].name + "</h2>"; for (j in myObj.cars[i].models) { x += myObj.cars[i].models[j] + "<br>"; } }
Complete Code Accessing For Nested JSON Array Values With JavaScript
<!DOCTYPE html> <html> <head> <title>How To Access Nested JSON Array Values With JavaScript</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <br> <div class="text-center"> <h1 id="color" style="color: tomato">How To Access Nested JSON Array Values With JavaScript</h1> </div> <br> <div class="well"> <h2 id="demo1"></h2> </div> <script> var myObj, i, j, x = ""; myObj = { "name":"Shiva", "age":30, "cars": [ {"name":"Ford", "models":["Fiesta", "Focus", "Mustang"]}, {"name":"BMW", "models":["320", "X3", "X5"]}, {"name":"Fiat", "models":["500", "Panda"] } ] } for (i in myObj.cars) { x += "<h2>" + myObj.cars[i].name + "</h2>"; for (j in myObj.cars[i].models) { x += myObj.cars[i].models[j] + "<br>"; } } document.getElementById("demo1").innerHTML = x; </script> </div> </body> </html>