5 Ways to loop through array objects in JavaScript

In this post, we will be going to explore 5 Ways to loop through array objects in JavaScript. There are many situations where we have to loop through the objects and array of objects. Before ES5 there was no simple way to iterate over the array of objects.

Before ES5, We were using the Simple for loop to iterate over the object. In ES5 for each loop is introduced.ES 6 Introduced the For-of loop to iterate on objects.

1. For In Loop through array objects


For loop iterate non-symbol(object can have a String, Symbol as key type) properties of an object. One every iteration the property of the object is assigned to a variable.

Use: It is mostly used to check the property of an object.If we need to check some hold specific value. Let us understand with examples

let Students = [{     id:1,     name:"Jack",	 Section:'B'   },
   {     id:2,     name:"Ram",	 Section:'A'   },
  {    id:3,    name:"Sika",	Section:'A'  }]

for(let stu in Students){
   console.log(`${Students[stu].id} ${Students[stu].name}  ${Students[stu].Section}`);
}

Output:

1 Jack  B
2 Ram  A
3 Sika  A

2. Foreach loop to iterate over array objects


Foreach is introduced in ES5. The for-each loop calls a function(callback) on each element of the array once unlike map, and reduce. We call a callback function. Its return value is undefined.

Syntax

array.callback([value, index, array]))

Parameters

The callback function for each loop has three arguments

  • Value:It is the current array element.
  • Index(optional): the integer position of current element in the array
  • Array(optional):on which we are executing the foreach() loop

Note: The number of elements executes by the foreach will be assigned before the first call of the callback function. Otherwise, the callback function not gets called on these elements.

Cons: We can’t break, return the value for each loop. The for-each loop is slower than for loop.

Better understand with an example:

//foreach on array of objects


let Students = [   {id:1,name:"Jack",Section:'B'},
   {     id:2, name:"Ram", Section:'A'    },
  {    id:3,    name:"Sika",Section:'A'  } ]

Students.forEach(function(obj) {
  console.log('Name: ' + obj.name);
  console.log('ID:' + obj.id);
  console.log('Section: ' + obj.Section);
  
})


//another way without writing hard code Key 
 Students.forEach((item, i) => {
       for(let key in item) {
           console.log(`${key}: ${item[key]}`);
       }
    });


Output

Name: Jack
ID:1
Section: B
Name: Ram
ID:2
Section: A
Name: Sika
ID:3
Section: A

//without hard code key name

id: 1
name: Jack
Section: B
id: 2
name: Ram
Section: A
id: 3
name: Sika
Section: A

We can write the cleaner and less code using ES6 arrow function(=>).Let us Understand with example

  let Students = [   {id:1,name:"Jack",Section:'B'},
   {     id:2, name:"Ram", Section:'A'   },  {    id:3,    name:"Sika",Section:'A'
  }]
Students.forEach((stu)=>console.log(stu.id +' '+ stu.name+' '+stu.Section));

Output

1 Jack B
2 Ram A
3 Sika A

3. For loop to iterate over array objects


For-of loop introduced in ES6. We use it to loop over the values of an object with the unique property object. It is a substitution of for-in and for-each loops, to loop on the iterable object including (Array, String, Map, Set, Nodelist, TypeArray) and custom iterable object.

Syntax

for (variable of iterableobj) {
  //code here
}

Parameters

  • Variable: When we loop through the iterableobj, different properties of iterableobj assign to a variable. We can declare a variable with const, let, var
  • iterableobj: On which we are running for of loop.

Example Iterate Over an array of Object

let Students = [{     id:1,     name:"Jack",	 Section:'B'   },
   {     id:2,     name:"Ram",	 Section:'A'   },
  {    id:3,    name:"Sika",	Section:'A'  }]

for(let stu of Students){
  console.log(stu.id +' '+ stu.name+' '+stu.Section) 
  }

Output:

1 Jack B
2 Ram A
3 Sika A

4. array. map() to loop through the array of object


In this javascript program, we have used an array.map() function to loop through an array of objects and write their corresponding key-value pair. Let us understand with an example.

let Students = [   {id:1,name:"Jack",Section:'B'},
   {     id:2, name:"Ram", Section:'A'    },
  {    id:3,    name:"Sika",Section:'A'  } ]


Students.map(({id, name, Section})=>{ 

  console.log(`Student Id :${id} name : ${name} Section : ${Section}`)

});

Output

Student Id :1 name : Jack Section : B
Student Id :2 name : Ram Section : A
Student Id :3 name : Sika Section : A

Iterate over each key in a given array of objects and print their key-value pair on each iteration using the object.entries()

 
Object.entries(Students).map(([key,object]) => 
{    console.log(`iterate through  key : ${key}`);

    Object.entries(object).map(([innerKey, value]) => {
        console.log(`${innerKey} : ${value}`);
    });
  console.log() 
});

Output

iterate through  key : 0
id : 1
name : Jack
Section : B

iterate through  key : 1
id : 2
name : Ram
Section : A

iterate through  key : 2
id : 3
name : Sika
Section : A

6. iterate keys, values, key-values of object array


In this technique, First, we convert the object into an array and iterate over the array of objects. Different ways to convert an object into an array
1.Object.keys(object): Return array of object keys.
2.Object.values(object): return array of object values
3.Object.entries(object) : return array of key,values of object.

Let us understand with example

let Students = 
   {     id:1,
     name:"Jack",
	 Section:'B'
   }

//get the keys
const keys = Object.keys(Students)
console.log('Keys=\n'+keys)

//Get the key and values
 entries = Object.entries(Students)
 console.log('entries=\n'+entries)
 
 //Get the Values
 values = Object.values(Students)
 
 console.log('Values=\n'+values)

Output:

Keys=
id,name,Section
entries=
id,1,name,Jack,Section,B
Values=
1,Jack,B

1.Foreach Loop to iterate on Object.keys()


console.log('Id  name  Section')
Object.keys(Students).forEach(stu =>  
  console.log(`${Students[stu].id}  ${Students[stu].name}  ${Students[stu].Section}`));

Output:

  Id  name  Section
1  Jack  B
2  Ram  A
3  Sika  A

2. Foreach loop to iterate on object.entries()

 console.log('Id  name  Section')
Object.entries(Students).forEach(stu =>
   console.log(`${stu[1].id}  ${stu[1].name}  ${stu[1].Section}`));
   

//another way
  Object.entries(Students).forEach(([key, val]) => console.log(key,':', val));

Output:

Id  name  Section
1  Jack  B
2  Ram  A
3  Sika  A

0 : { id: 1, name: 'Jack', Section: 'B' }
1 : { id: 2, name: 'Ram', Section: 'A' }
2 : { id: 3, name: 'Sika', Section: 'A' }

3. Convert to an array iterate objects.values()


Object.values(Students).forEach(stu =>
   console.log(`${stu.id}  ${stu.name}  ${stu.Section}`));


Output:

1 Jack B
2 Ram A
3 Sika A

Summary

We have learned 4 Ways to loop through array objects in JavaScript We can use any of them as per need.