How To Access Nested JSON Array Values With JavaScript

admin_img Posted By Bajarangi soft , Posted On 08-10-2020

If the JSON data describes an array, and each element of that array is of a basic type (number, string, boolean, or null) so today we discuss how to print nested json array with java script

How To Access Nested JSON Array Values With JavaScript

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


To access arrays inside arrays, use a for-in loop for each array:

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>

 

Related Post