Loading...
New webinar: "The Remote Job Search: My Microverse Journey" with graduate Paul Rail
Watch Now

Topics

There may be times where you feel you need to make a loop through the array of JSON objects in JavaScript. However, you no longer need to worry about this, as it can be done using an array of numbers, strings, or objects. There are numerous ways of looping in JavaScript and throughout this article we’ll help you grasp them.

There are a few types of ways to categorize the loops in JavaScript. These are essential to know as they play a significant role in understanding the concept.

Categories of Loops in JavaScript

The ‘For’ Loop

The For Loop comes first because of its simplicity and ease of use. It is a very user-friendly kind of loop that runs with a method of using a counter. 

The value is first set with an appropriate condition, which is also called ‘initializing a loop’. Next, the terminal or final value is specified. The For Loop makes things really easy when you need to run a set of codes multiple times.

The For Loop is further divided into:

1. Using an array

The following piece of code is a perfect example of how to use a for loop through an array. 

{% code-block language="js" %}
var numbers = [ 10, 20, 30, 40, 50] 
for (var i=0; i < numbers.length; i++) {
   console.log(numbers[i])
}
{% code-block-end %}
Here, I have used all the numbers in the form of an array, then printed each of them in a console window. In the same way, you can make a loop through an array of strings.

2. Making a loop through DOM elements

The For loop can also be used to alter colors. Consider a situation where you want to choose a particular color for all the anchors of your page. In order to do so, use the following piece of code.
 {% code-block language="js" %}
var elements = document.querySelectorAll("a");
for (var i=0; i<elements.length; i++) {
   elements[i].style.color = "red";
}
{% code-block-end %}

When you look at the above code, things might not seem very clear. 

I first used `document.querySelectorAll("a")` to get all of my anchors in the array format. Once that was done, the next step looped all the array and changed its color. 

Here, we used the color red, but you may choose any color in the code and the anchors of your page will appear that particular color. 

In order to better understand this visually, here’s the output of when I ran this code on the W3Schools site:

You can see that the color of the anchors has been changed to red. 

The ‘For In’ Loop

Another way of looping is the For In Loop. Unlike the For Loop, this loop won’t be using a counter. So this makes the whole process even more simple and hassle-free. In fact, the For In Loop is essentially a simplified version of the For Loop.

The following are different ways of looping using the For In technique.

1. Looping through an Object Property

Here’s an example; you’ve got an object containing some properties and you need to look up each property and the value that it carries. Here’s how you would use the For In Loop to do so:
{% code-block language="js" %}
var person = {
   fname: "Nick",
   lname: "Jonas",
   age: 26
}; 
for (let x in person) {
   console.log(x + ": "+ person[x])
}
{% code-block-end %}

Looping Using JSON

JSON stands for JavaScript Object Notation. It’s a light format for storing and transferring data from one place to another. So in looping, it is one of the most commonly used techniques for transporting data that is the array format or in attribute values. 

Here’s an example that demonstrates the above concept.

{% code-block language="js" %}
jsonData ={
   one: [11, 12, 13, 14, 15],
   two: [21, 22, 23],
   three: [31, 32]
}
{% code-block-end %}
JavaScript Object Notation also consists of a root, namely, the jsonData. It further contains three nodes that are called, “one”, “two”, and “three”. 

Here’s how you can withdraw a piece of information from JSON:

{% code-block language="js" %}
var json = {
   one: [11, 12, 13, 14, 15],
   two: [21, 22, 23],
   three: [31, 32]
}
};
for(var key in json.jsonData) {
   for (var key1 in json.jsonData[key]) {
       console.log(json.jsonData[key][key1])
   }
}
{% code-block-end %}
Above, I used two For In Loops to make use of JSON and extract information from it. One of those loops is the outer loop that runs three times. If you’re wondering why it needs to run three times, that’s because it has to cover the above-mentioned nodes.

The second loop is the inner loop which is meant to cover all the internal values. These internal values are those which are inside the three nodes. Once you run the code, you will get these kinds of results:

JSON Explained

If we go further in depth, there are a few more things you need to know about JSON.  The code that we just ran can also be expressed by including ‘[]’ to contain the above three nodes.

Here’s how it’s done:

{% code-block language="js" %}
jsonData:  [
   one: [11, 12, 13, 14, 15],
   two: [21, 22, 23],
   three: [31, 32]
]
{% code-block-end %}
Then, in the following piece of code, a blend of the two looping techniques of For and For In are used to withdraw all the information from JSON.

{% code-block language="js" %}
var json = {
   jsonData:  [
       {one: [11, 12, 13, 14, 15]},
       {two: [21, 22, 23]},
       {three: [31, 32]}
   ]
}; 
for (var i=0; i<json.jsonData.length; i++) {
   for (var key in json.jsonData[i]) {
       for (var j= 0; j<json.jsonData[i][key].length; j++) {
           console.log(json.jsonData[i][key][j])
       }
   }
}
{% code-block-end %}

Types of Loops and Their Uses

Now let’s have a look at different types of Loops and their uses. We shall discuss the “While” Loop, the “Do While Loop” and the “The ForEach() Loop”.

1. The “While” Loop

A While Loop also doesn’t have a counter and only runs if the specified condition is true.  Here’s an example demonstrating the while loop where the loop runs till infinity:

{% code-block language="js" %}
var infiniteValue = true;
while (infiniteValue) {
   console.log("Infinite")
}
{% code-block-end %}

2. Do While Loop

In this loop, there’s a defined condition that needs to be checked at the end of the process.

Here’s how you can use the Do While Loop in order to loop through XML(Extensible Markup Language):


3. The ForEach() Loop

This method is used for looping through an array element. Here’s an example of this:

{% code-block language="js" %}
var names = ["jerry", "tom", "pluto", "micky", "mini"];
names.forEach(function1);
function function1(currentValue, index) {
   console.log("Index in array is: "+index + " ::  Value is: "+currentValue);
}
{% code-block-end %}

Looping through JSON in more detail with examples

Example 1:

We're making a list of books and we enter the title as “Lord of the Rings” and the year as “1994“and the count of pages as “3000”. Similarly, a large number of objects can be created and once it’s done, we will have a large database:

{% code-block language="js" %}
var books = [
   {
       title: "Lord of the Rings",
       year: 1994,
       pages: 3000
   },
   {
       title: "1984",
       year: 1984,
       pages: 2000
   },
   {
       title: "Art of war",
       year: 2000,
       pages: 5000
   }
]
{% code-block-end %}
Now different things can be done with this database.

For example;

{% code-block language="js" %}
alert(books.length);
{% code-block-end %}
When we run this, the browser will display three. Essentially, with this, we checked that there are three objects in this array.

Keep in mind that in JSON, you need to separate your objects with a comma as you can see in the example.

Example 2

In this example, we are looping within the array.

{% code-block language="js" %}
for (i=0; i<books.length; i++){
   document.write(
       books.title + "<br />"
   );
}
{% code-block-end %}

Once, I run this, all of the titles in my database would be displayed as shown below.

Now, that should help you better understand how to loop through JSON. I've also created a video walkthrough of some examples in real-time to help you better understand this concept.


Conclusion

This article and video tutorial should have helped you understand the concept of looping through the array of JSON objects in JavaScript. Now you should be able to apply this tutorial to do things like running the For Loop, the For In Loop, the While Loop, and so on.

Happy Coding!

To learn more about Microverse, and joining our supportive community of remote software developers, get started below!


Subscribe to our Newsletter

Get Our Insights in Your Inbox

Career advice, the latest coding trends and languages, and insights on how to land a remote job in tech, straight to your inbox.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
We use own and third party cookies to; provide essential functionality, analyze website usages, personalize content, improve website security, support third-party integrations and/or for marketing and advertising purposes.

By using our website, you consent to the use of these cookies as described above. You can get more information, or learn how to change the settings, in our Cookies Policy. However, please note that disabling certain cookies may impact the functionality and user experience of our website.

You can accept all cookies by clicking the "Accept" button or configure them or refuse their use by clicking HERE.