Horje
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.

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.

JavaScript
const obj = {
    "company": 'GeeksforGeeks',
    "contact": '+91-9876543210',
    "city": 'Noida'
};

for (const key in obj) {
    console.log(`${key}: ${obj[key]}`);
}

Output
company: GeeksforGeeks
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.

JavaScript
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

Iterate JSON Object using Object.keys() and Array forEach Method

You can use Object.keys() to get an array of the keys of the JSON object and then iterate over this array using the forEach method. Object.keys(obj) returns an array of the keys of the JSON Object (obj). The forEach method is used to iterate over this array of keys. Inside the forEach loop, you can access the value of each property using obj[key].

Example: This code iterates over the keys of the JavaScript object ‘obj’ using Object.keys(), printing each key along with its corresponding value.

JavaScript
const obj = {
    "company": 'GeeksforGeeks',
    "contact": '+91-9876543210',
    "city": 'Noida'
};

Object.keys(obj).forEach(key => {
    console.log(`${key}: ${obj[key]}`);
});

Output
company: GeeksforGeeks
contact: +91-9876543210
city: Noida

Iterate JSON Object using Object.entries() and Array forEach Method

If you need both the keys and values of the JSON object, you can use Object.entries() to get an array of [key, value] pairs and then iterate over this array. Object.entries(obj) returns an array of [key, value] pairs from the JSON Object (obj). The forEach method is used to iterate over this array of entries. Inside the forEach loop, you can directly access both the key and value of each property.

Example: This code iterates over the entries (key-value pairs) of the JavaScript object ‘obj’ using Object.entries(), printing each key-value pair.

JavaScript
const obj = {
    "company": 'GeeksforGeeks',
    "contact": '+91-9876543210',
    "city": 'Noida'
};

Object.entries(obj).forEach(([key, value]) => {
    console.log(`${key}: ${value}`);
});

Output
company: GeeksforGeeks
contact: +91-9876543210
city: Noida

Iterate JSON Object using for…of Loop with Object.entries() Method

You can also use the for…of loop in combination with Object.entries() to iterate over the [key, value] pairs of the JSON object. Object.entries(obj) returns an array of [key, value] pairs from the JSON Object (obj). The for…of loop iterates over this array of entries. Inside the loop, you can directly access both the key and value of each property.

Example: This code iterates over the entries (key-value pairs) of the JavaScript object ‘obj’ using Object.entries(), destructuring each entry into ‘key’ and ‘value’, and then printing them.

JavaScript
const obj = {
    "company": 'GeeksforGeeks',
    "contact": '+91-9876543210',
    "city": 'Noida'
};

for (const [key, value] of Object.entries(obj)) {
    console.log(`${key}: ${value}`);
}

Output
company: GeeksforGeeks
contact: +91-9876543210
city: Noida

Using Object.values() and Array forEach Method

Another approach to iterate over a JSON object in JavaScript is to use the Object.values() method in combination with the forEach method. This approach is particularly useful when you are only interested in the values of the JSON object and do not need the keys. The Object.values() method returns an array of the object’s own enumerable property values, which can then be iterated over using forEach.

Example: The following example demonstrates how to iterate over the values of a JSON object using Object.values() and forEach.

JavaScript
const obj = {
  name: 'Alice',
  age: 30,
  profession: 'Engineer'
};

function iterateValues(obj) {
  Object.values(obj).forEach(value => {
    console.log(value);
  });
}

iterateValues(obj);
// Output:
// Alice
// 30
// Engineer

Output
Alice
30
Engineer





Reffered: https://www.geeksforgeeks.org


JavaScript

Related
Shadowing Properties in JavaScript Shadowing Properties in JavaScript
How to Parse JSON Data in JavaScript ? How to Parse JSON Data in JavaScript ?
How to Convert Object to Array in JavaScript? How to Convert Object to Array in JavaScript?
JavaScript Program to Add Two Promises JavaScript Program to Add Two Promises
How to Convert Callback to Promise in JavaScript ? How to Convert Callback to Promise in JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16