4 Ways to loop through array objects in JavaScript

JavaScript

In this post, we will be going to explore 4 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 assigned to a variable.

Use:It is mostly use to check on property of an object.If we need to check some hold specific value.

Example

for (variable in object)
{
//code here
}

Better we will understand with an example.

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

callback function in 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:

 let fruits = [
    "apple",  "orange",  "Banana",  "KIWI","Cherry"
]
fruits.forEach(function (fruit, index) {
if (fruit === 'KIWI') return;
console.log(`${fruit}  ${index}`);

Output

apple  0
orange  1
Banana  2
Cherry  4

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 of 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 those include(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

Iterate Over a string

const iterableobj = 'for of loop';

for (const str of iterableobj) {
  console.log(str);
}

Output

f
o
r
 
o
f
 
l
o
o
p

4. iterate keys, values, entries of object


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()

let Students = [{
     id:1,
     name:"Jack",
	 Section:'B'
   },
   {
     id:2,
     name:"Ram",
	 Section:'A'
	 
   },
  {
    id:3,
    name:"Sika",
	Section:'A'
  }]
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()

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

Output:

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

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

let Students = [{
     id:1,
     name:"Jack",
	 Section:'B'
   },
   {
     id:2,
     name:"Ram",
	 Section:'A'
	 
   },
  {
    id:3,
    name:"Sika",
	Section:'A'
  }]
let values = Object.values(Students)
for (let value of values) 
{
  console.log(`${value.id} ${value.name} ${value.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.