0

I would like to know how to loop multiple objects inside an array in vanilla JavaScript.

The below example doesn't work and I don't know why.

<!DOCTYPE html>
<html>
<body style="background-color: #d89797;">
  <h2>JavaScript Arrays</h2>
  <p>The best way to loop through an array is using a standard for loop:</p>
  <p id="demo"></p>
  <script>
    var fruits, text, fLen, i;

    fruits = [{
        "customerID": "10",
        "countInvoices": "42",
        "name": "Xuseen"
      },
      {
        "customerID": "100",
        "countInvoices": "420",
        "name": "khalid khalid"
      }
    ];
    fLen = fruits.length;
    text = "<ul>";

    for (i = 0; i < fLen; i++) {
      text += "<li>" + fruits[i] + "</li>";
    }

    text += "</ul>";
    document.getElementById("demo").innerHTML = text;
  </script>
</body>
</html>

Thanks.

Rick
  • 4,030
  • 9
  • 24
  • 35
mohdadawe
  • 25
  • 1
  • 4

2 Answers2

0

You need to add array keys which you need to print out.

Here updated code:

 var fruits, text, fLen, i;

fruits = [{"customerID":"10", "countInvoices":"42", "name":"Xuseen"},
        {"customerID":"100", "countInvoices":"420", "name":"khalid khalid"}];

fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
    text += "<li>ID: " + fruits[i]['customerID'] + " countInvoices: "+fruits[i]['countInvoices']+" and NAME ="+fruits[i]['name']+" </li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;

Good luck.

Kristaps
  • 11
  • 4
0

You have to iterate over the object inside your array as well.

var fruits, text, fLen, i;
fruits = [{"customerID":"10", 
    "countInvoices":"42", 
    "name":"Xuseen"},
    {"customerID":"100", 
    "countInvoices":"420", 
    "name":"khalid khalid"}];

    fLen = fruits.length;
    text = "<ul>";
    for (i = 0; i < fLen; i++) {
      for (key in fruits[i]) {
          text += "<li>" + key + ":" + fruits[i][key] + "</li>";
        }
    }
    text += "</ul>";
    document.getElementById("demo").innerHTML = text;
<h2>JavaScript Arrays</h2>

<p>The best way to loop through an array is using a standard for loop:</p>

<p id="demo"></p>
Carle B. Navy
  • 1,156
  • 10
  • 28