Iterate JSON Object using for…in Loop
The for…in loop is a simple and basic method to iterate over the properties of a JSON object. The for…in loop iterates over the keys of the JSON Object (obj). Inside the loop, you can access the value of each property using obj[key]. This method allows you to perform operations on both the keys and values of the JSON object.
Example 1: Iterating Over JavaScript Object Properties: This code iterates over the properties of a JavaScript object ‘obj’ using a for…in loop, printing each key-value pair to the console.
const obj = {
"company": 'w3wiki',
"contact": '+91-9876543210',
"city": 'Noida'
};
for (const key in obj) {
console.log(`${key}: ${obj[key]}`);
}
Output
company: w3wiki contact: +91-9876543210 city: Noida
Example 2: This code iterates over a nested JavaScript object ‘obj’, printing each key along with its associated values, including nested arrays and their respective properties.
const obj = {
"Data Structures": [
{
"Name" : "Trees",
"Course" : "Intoduction of Trees",
"Content" : [ "Binary Tree", "BST", "Generic Tree"]
},
{
"Name" : "Graphs",
"Topics" : [ "BFS", "DFS", "Topological Sort" ]
}
]
};
for (const key in obj) {
console.log(`${key}:`);
obj[key].forEach(item => {
console.log(`\tName: ${item.Name}`);
if (item.Course) {
console.log(`\tCourse: ${item.Course}`);
}
if (item.Content) {
console.log(`\tContent: ${item.Content.join(', ')}`);
}
if (item.Topics) {
console.log(`\tTopics: ${item.Topics.join(', ')}`);
}
console.log();
});
}
Output
Data Structures: Name: Trees Course: Intoduction of Trees Content: Binary Tree, BST, Generic Tree Name: Graphs Topics: BFS, DFS, Topological Sort
How to Iterate JSON Object in JavaScript?
JSON (JavaScript Object Notation) is a lightweight data-interchange format commonly used for exchanging data between a server and a web application. In JavaScript, JSON objects are similar to JavaScript objects, and iterating over them is a common task. In this article, we’ll explore different approaches to iterate over a JSON object in JavaScript, along with complete code examples and explanations.
Table of Content
- Using for…in Loop
- Using Object.keys() and Array forEach Method
- Using Object.entries() and Array forEach Method
- Using for…of Loop with Object.entries()
Contact Us