How to loop through an array containing multiple objects and access their properties in JavaScript ?
It’s easy to loop through the array of elements as we can access the elements by the array indexes. But it is not the case with objects as the object is a pair of keys and values indexing doesn’t work with an array of objects.
So the process of looping through the array of objects is different from the traditional looping of the array. There are different methods like object.keys(), object.values(), object.entries() in Javascript to access the keys and values of objects easily.
There are many ways to loop through the array of objects. Let’s look at them one by one:
Approach 1: Using for…in loop
The properties of the object can be iterated over using a for..in loop. The value of each key of the object can be found by using the key as the index of the object.
Example:
Javascript
<script> const Teachers = [ { name: 'saritha' , subject: 'Maths' }, { name: 'ahim' , subject: 'science' }, { name: 'sneha' , subject: 'Social' }] Teachers.forEach(teacher => { for (let value in teacher) { console.log(`${teacher[value]}`) } }) </script> |
Output:
saritha Maths ahim science sneha Social
Approach 2: Using Object.keys() Method
The Object.keys() method in JavaScript returns an array whose elements are strings corresponding to the enumerable properties. The Object.keys() method returns only the own property names.
Example:
Javascript
<script> const Teachers = [ { name: 'saritha' , subject: 'Maths' }, { name: 'ahim' , subject: 'science' }, { name: 'sneha' , subject: 'Social' }] for (let teacher in Object.keys(Teachers)) { for (let key in Teachers[teacher]) { console.log(Teachers[teacher][key]); } } </script> |
Output:
saritha Maths ahim science sneha Social
Approach 3: Using object.values() Method
The Object.values() method is used to return an array whose elements are the enumerable property values found on the object. we iterate through that array and get only the properties of that object.
Example:
Javascript
<script> const Teachers = [ { name: 'saritha' , subject: 'Maths' }, { name: 'ahim' , subject: 'science' }, { name: 'sneha' , subject: 'Social' }] for (const value of Object.values(Teachers)) { for (let v in value) { console.log(value[v]); } } </script> |
Output:
saritha Maths ahim science sneha Social
Approach 4: Using object.entries() method
The Object.entries() method in JavaScript returns an array consisting of enumerable property [key, value] pairs of the object. we iterate through that array using for..in loop and get only the properties of that object.
Javascript
<script> const Teachers = [ { name: 'saritha' , subject: 'Maths' }, { name: 'ahim' , subject: 'science' }, { name: 'sneha' , subject: 'Social' }] for (const entry of Object.entries(Teachers)) { for (let value in entry[1]) { console.log(entry[1][value]); } } </script> |
Output:
saritha Maths ahim science sneha Social
Please Login to comment...