Thursday, 28 May 2020

JSON - How to loop an Object and get all the Keys and Values? | JSON Tutorial

Loved this tutorial?

Subscribe to Ram N Java on YouTube for simple, practical coding tutorials and programming tips!

Subscribe Now

Looping Through a JSON Object

When working with JSON in JavaScript, you'll often encounter objects containing key-value pairs where you need to read every property dynamically. Instead of accessing each property manually by name, you can iterate through the entire object using a simple loop.

The Sample JSON Object

Let's look at an example JavaScript object representing person details:

const person = {
  "name": "John",
  "age": 30,
  "city": "New York"
};

Extracting Keys and Values with a for...in Loop

The standard way to loop through properties in a JavaScript object is the for...in statement:

  • The Key: The loop variable holds the property name (key) for each iteration.
  • The Value: Bracket notation (object[key]) retrieves the matching value dynamically.
for (let key in person) {
  let value = person[key];
  console.log("Key: " + key + " | Value: " + value);
}

Key Takeaway

Using dynamic bracket access gives you total flexibility, especially when object properties change or are received dynamically from an API.


Recommended Next Tutorials

No comments:

Post a Comment

Tutorials