How to Iterate JSON Object in JavaScript?
Last Updated :
21 Aug, 2024
JSON (JavaScript Object Notation) is a lightweight data-interchange format commonly used to exchange data between a server and a web application. 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 the 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]}`);
}
Outputcompany: 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();
});
}
OutputData Structures:
Name: Trees
Course: Intoduction of Trees
Content: Binary Tree, BST, Generic Tree
Name: Graphs
Topics: BFS, DFS, Topological Sort
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]}`);
});
Outputcompany: GeeksforGeeks
contact: +91-9876543210
city: Noida
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}`);
});
Outputcompany: GeeksforGeeks
contact: +91-9876543210
city: Noida
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', // Define an object with company name
"contact": '+91-9876543210', // Add contact information
"city": 'Noida' // Specify the city
};
// Iterate over each key-value pair in the object
for (const [key, value] of Object.entries(obj)) {
console.log(`${key}: ${value}`); // Log the key and its corresponding value
}
Outputcompany: GeeksforGeeks
contact: +91-9876543210
city: Noida
Similar Reads
How to iterate over a JavaScript object ?
Iteration involves looping through the object's properties one by one. Depending on the method used, you can access and manipulate different levels of properties efficiently. Here are several methods.There are many methods to iterate over an object which are discussed below: Table of ContentUsing fo
3 min read
How to Check if Object is JSON in JavaScript ?
JSON is used to store and exchange data in a structured format. To check if an object is JSON in JavaScript, you can use various approaches and methods. There are several possible approaches to check if the object is JSON in JavaScript which are as follows: Table of Content Using Constructor Type Ch
2 min read
Converting JSON text to JavaScript Object
Pre-requisite: JavaScript JSON JSON (JavaScript Object Notation) is a lightweight data-interchange format. As its name suggests, JSON is derived from the JavaScript programming language, but itâs available for use by many languages including Python, Ruby, PHP, and Java and hence, it can be said as l
3 min read
How to Parse JSON in JavaScript ?
Parse JSON in JavaScript, accepting a JSON string as input and returning a corresponding JavaScript object with two methods, using JSON.parse() for parsing JSON strings directly and employing the fetch API to parse JSON responses from web APIs. These techniques are crucial for seamless data manipula
2 min read
Are Objects Iterable in JavaScript?
In JavaScript, plain objects are not iterable by default, meaning you cannot directly use constructs like for...of loops or the spread operator (...) with them. However, arrays (a), strings, maps, and sets are inherently iterable. Understanding Iterables in JavaScriptAn iterable is an object that im
2 min read
How to Master JSON in JavaScript?
JSON is a text format for representing structured data, typically in the form of key-value pairs. It primarily sends data between a server and a client, especially in web APIs.Objects are enclosed in curly braces {} and contain key-value pairs.Arrays are enclosed in square brackets [] and hold value
5 min read
JavaScript | Add new attribute to JSON object
The task is to add a JSON attribute to the JSON object. To do so, Here are a few of the most used techniques discussed.Example 1: This example adds a prop_11 attribute to the myObj object via var key. html <!DOCTYPE HTML> <html> <head> <title> JavaScript | Add new attribute t
2 min read
How to change JSON String into an Object in JavaScript ?
In this article we are going to learn how to change JSON String into an object in javascript, JSON stands for JavaScript object notation. It is the plain format used frequently as a communication medium on the internet. It appears close to OOP language like JavaScript but cannot be accessed like Jav
3 min read
How to iterate over Map elements in JavaScript ?
Map() is very useful in JavaScript it organises elements into key-value pairs. This method iterates over each element in an array and applies a callback function to it, allowing for modifications before returning the updated array." The Map() keyword is used to generate the object. The map() method
3 min read
How to Convert JSON Object to CSV in JavaScript ?
JSON (JavaScript Object Notation) and CSV (Comma-Separated Values) are two widely used formats, each with its own strengths and applications. Fortunately, JavaScript provides powerful tools to facilitate the conversion process between these formats. These are the following approaches: Table of Conte
3 min read