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