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.
const obj = {
"company": 'w3wiki',
"contact": '+91-9876543210',
"city": 'Noida'
};
for (const [key, value] of Object.entries(obj)) {
console.log(`${key}: ${value}`);
}
Output
company: w3wiki contact: +91-9876543210 city: Noida
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