Thursday, 28 May 2020

Nested Arrays in JSON Object | JSON Tutorial

Want more web development tutorials?

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

🔔 Subscribe to the Channel

What Are Nested Arrays in JSON?

In real-world web applications and API responses, data structures are rarely flat. Often, an object contains an array of items, and each of those items contains another array inside it. This structure is called a nested array.

For example, a user profile might have a list of cars, and each car might have its own list of specific models. Knowing how to step through both levels is a vital skill for handling modern web data.

Iterating with Nested Loops

To access every element stored in a nested array, you combine an outer loop and an inner loop:

  • Outer Loop: Steps through the main array (such as car brands).
  • Inner Loop: Runs through each item in the sub-array (such as individual car models) for that specific parent item.

Step-by-Step Code Example

Here is a complete, beginner-friendly example showing how to declare an object with nested arrays and extract all the inner values:

// Sample JSON object with nested arrays
const myObject = {
  "name": "John",
  "age": 30,
  "cars": [
    { "name": "Ford", "models": ["Fiesta", "Focus", "Mustang"] },
    { "name": "BMW", "models": ["320", "X3", "X5"] },
    { "name": "Fiat", "models": ["500", "Panda"] }
  ]
};

// Loop through each car brand
for (let i = 0; i < myObject.cars.length; i++) {
  console.log("Brand: " + myObject.cars[i].name);

  // Loop through the models array inside the current car
  for (let j = 0; j < myObject.cars[i].models.length; j++) {
    console.log("  Model: " + myObject.cars[i].models[j]);
  }
}

How It Works:

  • Outer Loop (i): Accesses each object in the cars array one by one.
  • Targeting the Inner Array (myObject.cars[i].models): Points directly to the array of models for that specific vehicle.
  • Inner Loop (j): Loops through every model name within that sub-array and prints it out.

Summary

Mastering nested loops allows you to handle deep, multi-level JSON structures with confidence, making it easy to display catalog lists, tables, and complex API responses on your web pages.

Related Tutorials from Ram N Java

Continue expanding your JSON skills with these related guides from the channel:

No comments:

Post a Comment

Tutorials