How to use For…in the loop In Javascript
The for…in loop iterates over the enumerable properties of an object, including those inherited from its prototype chain. It’s commonly used for iterating over object properties and performing operations based on each property’s value or key.
Example: Iterating through a JavaScript object with arrays and nested objects using built-in methods.
Javascript
let course = { title: "Java" , price: 30000, Instructors: [ "Kamal Sir" , "Anuv Sir" ], Materials: { book1: "Effective Java" , book2: "Head First Java" , }, }; for (let key in course) { if (course.hasOwnProperty(key)) { console.log(key, course[key]); } } |
title Java price 30000 Instructors [ 'Kamal Sir', 'Anuv Sir' ] Materials { book1: 'Effective Java', book2: 'Head First Java' }
How to Iterate JavaScript Object Containing Array and Nested Objects ?
JavaScript provides us with several built-in methods through which one can iterate over the array and nested objects using the for…in loop, Object.keys(), Object.entries(), and Object.values(). Each method serves a distinct purpose in iterating over object properties, keys, and values which are explained as follows:
Table of Content
- Using For…in the loop
- Using Object.keys() method
- Using Object.entries() method
- Using Object.values() method