How to loop through a plain object with the objects as members in JavaScript ?
Last Updated :
20 Jul, 2023
Looping through a plain JavaScript object with objects as members means iterating over each property of the object and accessing its values, which may also be objects. This is a common task in JavaScript, especially when dealing with JSON data or APIs.
There are several ways to loop through a plain JavaScript object with objects as members. Here are four common approaches
- Using For...in loop
- Using Object.keys()
- Using Object.entries()
- Using Object.Values()
This approach uses a for...in loop to iterate over each property of the object and access its values. For each property, the loop sets the key as the name of the property and the value as the value of the property. This approach is useful when you want to perform a similar action for each property of the object.
Syntax:
//for...in loop
for (let key in object) {
// do something with object[key]
}
Example: Using a for...in loop to iterate over an object with objects as members.
JavaScript
let person = {
name: "John",
age: 30,
address: {
street: "123 Main St",
city: "Anytown",
state: "CA",
zip: "12345"
}
};
for (let key in person) {
console.log(key + ": " + person[key]);
};
Outputname: John
age: 30
address: [object Object]
This approach uses the Object.keys() method to get an array of all the keys in the object. It then uses the forEach() method to iterate over each key in the array and access its corresponding value. This approach is useful when you want to perform a specific action for each key in the object.
Syntax:
// Object.keys()
Object.keys(object).forEach(function (key) {
// do something with object[key]
});
Example: Using Object.keys() to iterate over an object with objects as members
JavaScript
const myObj = {
prop1: { name: 'John', age: 25 },
prop2: { name: 'Sarah', age: 30 },
prop3: { name: 'Tom', age: 20 }
};
const newArray = Object.keys(myObj).map(key => {
const obj = myObj[key];
return { ...obj, id: key };
// Adding an id property to the object
});
console.log(newArray);
Output[
{ name: 'John', age: 25, id: 'prop1' },
{ name: 'Sarah', age: 30, id: 'prop2' },
{ name: 'Tom', age: 20, id: 'prop3' }
]
This approach uses the Object.entries() method to get an array of all the key-value pairs in the object. It then uses the forEach() method to iterate over each key-value pair and access the value, which could be an object. This approach is useful when you want to perform a specific action for each key-value pair in the object.
Syntax:
// Object.entries()
Object.entries(object).forEach(function([key, value]) {
// do something with value (which could be an object)
});
Example: Using Object.entries() to iterate over an object with objects as members.
JavaScript
let person = {
name: "John",
age: 30,
address: {
street: "123 Main St",
city: "Anytown",
state: "CA",
zip: "12345"
}
};
Object.entries(person).forEach(([key, value]) => {
console.log(key + ": " + value);
});
Outputname: John
age: 30
address: [object Object]
In this approach Object.values() returns an array of values from an object. It's used to loop through values, access properties in the person object, and printing names and ages.
Syntax:
Object.values(obj)
Example: Using Object.values(), loop through objects in the person object and log their names and ages.
JavaScript
const person = {
obj1: { name: "John", age: 30 },
obj2: { name: "Jane", age: 25 },
obj3: { name: "Bob", age: 40 }
};
Object.values(person).forEach(obj => {
console.log("name :" + obj.name, "age :" + obj.age);
});
Outputname :John age :30
name :Jane age :25
name :Bob age :40
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read