Loading...
JavaScript

Handling Array of Objects in JavaScript

If you are working with APIs, most of the time you will encounter arrays of objects. In this article you will learn how array of objects should be handled for further processing of received data or for presenting the data in UI in various forms like table, list and so on.

var arr = [ 
    { name: 'Ravi', age: 20 },
    { name: 'Ajay', age: 55 },
    { name: 'Henry', age: 15 }
];

Let’s say an API is returning an array of objects as shown in the example above. How would you loop and present the data in UI?

Looping Array of Object:

In order to display data in UI, you have to loop through each object (element) and display the property value. Since it is an array, you can use forEach() array method to loop through.

arr.forEach(function(element){
    // element is object here. 
    console.log(element.name, element.age);
})
// Output:
Ravi 20
Ajay 55
Henry 15

In the above example, we are passing a function in as an argument in the forEach() function. Such functions are know as callbacks in JavaScript.

You can learn more about callbacks in this article: What is Callback in JavaScript

The dot (.) operator is used to access object property values. Apart from element argument, the callback accepts second optional argument which provides the index of each element in the array.

arr.forEach(function(element, index){
    // element is object here. 
    console.log(index, element.name, element.age);
})
// Output:
0 Ravi 20
1 Ajay 55
2 Henry 15

Now, let’s try to display the data in a tabular form in UI using jQuery.


<script>
$(document).ready(function(){
   arr.forEach(function(element, index){
     index = index + 1;
     // Create row
     var row = "<tr><td>" 
             + index + "</td><td>"
             + element.name + "</td><td>" 
             + element.age + "</td></tr>";

     // Append row in table body
     $("#listUser tbody").append(row);
   })      
})
</script>

// Static HTML markup for table
<table id="listUser">
        <thead>
            <tr>
                <th>Sl</th>
                <th>Name</th>
                <th>Age</th>
            </tr>
        </thead>
        <tbody>  
            <!-- Rows will be added dynamically here -->  
        </tbody>
</table>

What we are doing here is looping through the array of object and creating table rows <tr> and adding value to <td> dynamically. Then appending each rows in the table body having id = "listUser". The loop will iterate three times as there are three elements in the array and consequently three table rows would be generated.

Here is complete example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Table Demo</title>
<style>
    table{
        width: 100%;
        margin-bottom: 20px;
		border-collapse: collapse;
    }
    table, th, td{
        border: 1px solid #cdcdcd;
    }
    table th, table td{
        padding: 10px;
        text-align: left;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
     var arr = [ 
        { name: 'Ravi', age: 20 },
        { name: 'Ajay', age: 55 },
        { name: 'Henry', age: 15 }
	 ];
     arr.forEach(function(element, index){
       index = index + 1;
       // Create row
       var row = "<tr><td>" 
             + index + "</td><td>"
             + element.name + "</td><td>" 
             + element.age + "</td></tr>";

       // Append row in table
       $("#listUser tbody").append(row);
     })    
  });    
</script>
</head>
<body>
    <table id="listUser">
        <thead>
            <tr>
                <th>Sl</th>
                <th>Name</th>
                <th>Age</th>
            </tr>
        </thead>
        <tbody>
            <!-- Rows will be added dynamically here -->  
        </tbody>
    </table>
</body> 
</html>

Add the above code in a HTML file and open it in a browser. You would see a dynamically generated table as shown below:

Handling Array of Objects in JavaScript

If you found this article useful, please leave your thoughts in the comment box below.

You may also like:
Important JavaScript Array Methods
Sort Array of Objects by Property Value in JavaScript

Share this article with your friends
Leave a Reply

Your email address will not be published. Required fields are marked *