Thursday, 28 May 2020

How to use a for-in loop to get JSON Array values? | JSON Tutorial

🚀 Master JavaScript & Java with Ease!

Subscribe to Ram N Java for clean, beginner-friendly coding guides!

🔔 Subscribe to Ram N Java

Introduction: Reading JSON Arrays with for-in

When working with JSON arrays in JavaScript, you have several ways to loop through elements. One convenient and compact technique is using the for-in loop.

In this guide, you will learn how the for-in loop works with JSON arrays, what it returns, and how to extract every value step-by-step.

1. Sample JSON Object with an Array

Let's look at an example JSON object that contains a property named cars holding an array of car models:

let myData = {
  "name": "Ram",
  "age": 30,
  "cars": ["Ford", "BMW", "Fiat"]
};

2. How the for-in Loop Works on Arrays

When applied to an array, the for-in loop iterates over each index (key) of the array (such as 0, 1, 2). You can then pass that index into bracket notation to read the actual value:

for (let i in myData.cars) {
  // 'i' holds the index (0, 1, 2)
  console.log(myData.cars[i]);
}

// Output:
// Ford
// BMW
// Fiat

3. Important Tips for Beginners

Keep these practical points in mind when using for-in:

  • The variable (e.g., i) represents the index, not the element itself.
  • Always access the element value using arrayName[i].
  • It offers a clean, concise alternative to standard indexed loops when reading properties or index lists.

Summary

The for-in loop gives you a quick and readable way to traverse through array indices in a JSON structure without manually managing counter initialization or increments.


Watch Next: Related Tutorials from Ram N Java

No comments:

Post a Comment

Tutorials