How Do I Access JSON Array Values Through For 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 for loop with JSON

How Do I Access JSON Array Values Through For 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 loop:

Example(1)
var myObj, i, x = "";
var myObj, i, x = "";
myObj = {
    "name":"John",
    "age":30,
    "cars":[ "Ford", "BMW", "Fiat" ]
};

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


Complete Code For Accessing JSON Array Values Through For  Loop

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

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

Related Post