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