Loop through an array of objects in JavaScript
This post will discuss how to loop through an array of objects in JavaScript.
1. Using Array.prototype.forEach() function
|
1 2 3 4 5 6 7 |
var obj = [ { name: 'Max', age: 23 }, { name: 'John', age: 20 }, { name: 'Caley', age: 18 } ]; obj.forEach(o => console.log(o)); |
2. Using for…of statement
|
1 2 3 4 5 6 7 8 9 |
var obj = [ { name: 'Max', age: 23 }, { name: 'John', age: 20 }, { name: 'Caley', age: 18 } ]; for (var value of obj) { console.log(value) } |
3. Using Object.entries() function
|
1 2 3 4 5 6 7 |
var obj = [ { name: 'Max', age: 23 }, { name: 'John', age: 20 }, { name: 'Caley', age: 18 } ]; Object.entries(obj).forEach(([_, value]) => console.log(value)); |
Or with for…of loop using destructuring assignment:
|
1 2 3 4 5 6 7 8 9 |
var obj = [ { name: 'Max', age: 23 }, { name: 'John', age: 20 }, { name: 'Caley', age: 18 } ]; for (const [_, value] of Object.entries(obj)) { console.log(value); } |
4. Using Object.keys() function
|
1 2 3 4 5 6 7 |
var obj = [ { name: 'Max', age: 23 }, { name: 'John', age: 20 }, { name: 'Caley', age: 18 } ]; Object.keys(obj).forEach(key => console.log(obj[key])); |
Or with for…of loop:
|
1 2 3 4 5 6 7 8 9 |
var obj = [ { name: 'Max', age: 23 }, { name: 'John', age: 20 }, { name: 'Caley', age: 18 } ]; for (const key of Object.keys(obj)) { console.log(obj[key]); } |
5. Using Object.values() function
|
1 2 3 4 5 6 7 |
var obj = [ { name: 'Max', age: 23 }, { name: 'John', age: 20 }, { name: 'Caley', age: 18 } ]; Object.values(obj).forEach(value => console.log(value)); |
Or with for…of loop:
|
1 2 3 4 5 6 7 8 9 |
var obj = [ { name: 'Max', age: 23 }, { name: 'John', age: 20 }, { name: 'Caley', age: 18 } ]; for (const value of Object.values(obj)) { console.log(value); } |
6. Using jQuery
|
1 2 3 4 5 6 7 8 9 10 11 |
const { JSDOM } = require("jsdom"); const { window } = new JSDOM(); var $ = require("jquery")(window); var obj = [ { name: 'Max', age: 23 }, { name: 'John', age: 20 }, { name: 'Caley', age: 18 } ]; $.each(obj, (_, value) => console.log(value)); |
7. Using Underscore/Lodash Library
|
1 2 3 4 5 6 7 8 9 |
var _ = require('underscore'); // or, use lodash var obj = [ { name: 'Max', age: 23 }, { name: 'John', age: 20 }, { name: 'Caley', age: 18 } ]; _.forEach(obj, (value, _) => console.log(value)); // or, use alias `_.each()` |
8. Using for…in statement
|
1 2 3 4 5 6 7 8 9 |
var obj = [ { name: 'Max', age: 23 }, { name: 'John', age: 20 }, { name: 'Caley', age: 18 } ]; for (var key in obj) { console.log(obj[key]); } |
That’s all about looping through an array of objects in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)