📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this post, I show you three different ways to loop or iterate over an Object in JavaScript.
3 Ways to Loop an Object in JavaScript
1. Using Object.keys() Method
var user = { firstName: 'Ramesh', lastName: 'Fadatare', emailId: 'ramesh@gmail.com', age: 29 } const keys = Object.keys(user) console.log(keys) // [apple, orange, pear] for (const key of keys) { console.log(" key :: " + key); console.log(" value :: " + user[key]); }
Output:
key :: firstName value :: Ramesh key :: lastName value :: Fadatare key :: emailId value :: ramesh@gmail.com key :: age value :: 29
2. Using Object.entries() Method
var user = { firstName: 'Ramesh', lastName: 'Fadatare', emailId: 'ramesh@gmail.com', age: 29 } const entries = Object.entries(user) for (const [key, value] of entries) { console.log(`Key Value Pair -> ${key} ${value}`) }
Output:
Key Value Pair -> firstName Ramesh Key Value Pair -> lastName Fadatare Key Value Pair -> emailId ramesh@gmail.com Key Value Pair -> age 29
3. Using Object.hasOwnProperty() Method
var user = { firstName: 'Ramesh', lastName: 'Fadatare', emailId: 'ramesh@gmail.com', age: 29 } for (var key in user) { if (user.hasOwnProperty(key)) { console.log(key + " -> " + user[key]); } }
Output:
firstName -> Ramesh lastName -> Fadatare emailId -> ramesh@gmail.com age -> 29
Comments
Post a Comment
Leave Comment