How Can I Access JSON Array Values Through For In Loop

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

The Array object is used to store multiple values in a single variable so Today we discuss how to access array value through loop with java script

How Can I Access JSON Array Values Through For In Loop

Creating an Array

Using an array literal is the easiest way to create a JavaScript Array.

Syntax:

var array_name = [item1, item2, ...];
 

Looping Array Elements

The safest way to loop through an array, is using a for in loop:

Example(1)

myObj = {
    "name":"John",
    "age":30,
    "cars":[ "Ford", "BMW", "Fiat" ]
};

for (i in myObj.cars) {
    x += myObj.cars[i] + "<br>";
}


Complete Code For Accessing JSON Array Values Through For In Loop
<!DOCTYPE html>
<html>
<head>
    <title>How Can I Access JSON Array Values Through For In Loop</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 Can I Access JSON Array Values Through For In Loop</h1>
    </div>
    <br>
    <div class="well">
        <h2 id="demo1"></h2>
        <h2 id="demo2"></h2>
    </div>
    <script>
        var myObj, i, x = "";
        myObj = {
            "name":"John",
            "age":30,
            "cars":[ "Ford", "BMW", "Fiat" ]
        };

        for (i in myObj.cars) {
            x += myObj.cars[i] + "<br>";
        }
        document.getElementById("demo1").innerHTML = x;
    </script>
</div>
</body>
</html>

 

Related Post