How to loop through arrays in JavaScript objects?


Looping through arrays inside objects is the same as looping through objects. We have to use 'for...in' loop to loop through arrays inside objects.

Example

In the following example, an object "obj" is defined. This object has an array in it. Using 'for...in' loop, the elements in that array are displayed as shown in the output. 

Live Demo

<html>
<body>
<script>
   var res = ""
   var obj = {
      "name":"Elon musk",
      "age":48,
      "companies": [
         {"location":"Newyork", "name":["Tesla", "Spacex", "Neuralink"]},
         {"location":"Florida", "name":["paypal", "solarcity"]},
      ]
   }
   for (var i in obj.companies) {
      res += "The companies in " + " "+ obj.companies[i].location + "</br>";
      for (var j in obj.companies[i].name) {
         res += obj.companies[i].name[j] + "</br>";
      }
   }
   document.write(res);
</script>
</body>
</html>

output

The companies in Newyork
Tesla
Spacex
Neuralink
The companies in Florida
paypal
solarcity
raja
Published on 15-Jul-2019 17:18:36
Advertisements