JSON Arrays

Working with ordered lists in JSON format

📋 What are JSON Arrays?

JSON Arrays are ordered lists of values enclosed in square brackets. They can contain strings, numbers, booleans, objects, or even other arrays.


// Simple JSON Array
[
    "apple",
    "banana",
    "orange"
]
                                    

Types of JSON Arrays

🔤

String Arrays

Arrays containing text values

["red", "green", "blue"]
🔢

Number Arrays

Arrays containing numeric values

[1, 2, 3, 4, 5]
📦

Object Arrays

Arrays containing JSON objects

[
  {"name": "John"},
  {"name": "Jane"}
]
🔄

Mixed Arrays

Arrays with different data types

["text", 42, true, null]

🔹 Basic JSON Array Examples

Here are common JSON array patterns:

🔸 Simple String Array

// Colors array
{
    "colors": ["red", "green", "blue", "yellow", "purple"]
}

🔸 Number Array

// Scores array
{
    "testScores": [85, 92, 78, 96, 88],
    "average": 87.8
}

🔸 Boolean Array

// Feature flags
{
    "features": [true, false, true, false, true]
}

🔹 Working with JSON Arrays in JavaScript

Access and manipulate JSON arrays using JavaScript:

// JSON string with array
const jsonString = '{"fruits": ["apple", "banana", "orange"]}';

// Parse JSON
const data = JSON.parse(jsonString);

// Access array
console.log(data.fruits);        // ["apple", "banana", "orange"]
console.log(data.fruits[0]);     // "apple"
console.log(data.fruits.length); // 3

// Loop through array
data.fruits.forEach((fruit, index) => {
    console.log(`${index}: ${fruit}`);
});

// Add new item
data.fruits.push("grape");
console.log(data.fruits); // ["apple", "banana", "orange", "grape"]

Console Output:

["apple", "banana", "orange"]

apple

3

0: apple

1: banana

2: orange

["apple", "banana", "orange", "grape"]

🔹 Arrays of Objects

One of the most common JSON patterns - arrays containing objects:

// Students array
{
    "students": [
        {
            "id": 1,
            "name": "Alice",
            "grade": "A",
            "subjects": ["Math", "Science"]
        },
        {
            "id": 2,
            "name": "Bob",
            "grade": "B",
            "subjects": ["English", "History"]
        },
        {
            "id": 3,
            "name": "Charlie",
            "grade": "A",
            "subjects": ["Math", "Art"]
        }
    ]
}
// Working with object arrays
const data = JSON.parse(jsonString);

// Find student by name
const alice = data.students.find(student => student.name === "Alice");
console.log(alice.grade); // "A"

// Get all student names
const names = data.students.map(student => student.name);
console.log(names); // ["Alice", "Bob", "Charlie"]

// Filter students with grade A
const aStudents = data.students.filter(student => student.grade === "A");
console.log(aStudents.length); // 2

🔹 Nested Arrays

Arrays can contain other arrays for complex data structures:

// Matrix (2D array)
{
    "matrix": [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ],
    "coordinates": [
        {"x": 10, "y": 20},
        {"x": 30, "y": 40}
    ]
}
// Accessing nested arrays
const data = JSON.parse(jsonString);

// Access matrix element
console.log(data.matrix[1][2]); // 6 (row 1, column 2)

// Access coordinate
console.log(data.coordinates[0].x); // 10

🔹 Real-World JSON Array Examples

🔸 Shopping Cart

{
    "cart": [
        {
            "productId": "P001",
            "name": "Laptop",
            "price": 999.99,
            "quantity": 1
        },
        {
            "productId": "P002", 
            "name": "Mouse",
            "price": 29.99,
            "quantity": 2
        }
    ],
    "total": 1059.97
}

🔸 API Response

{
    "users": [
        {
            "id": 1,
            "username": "john_doe",
            "email": "[email protected]",
            "active": true
        },
        {
            "id": 2,
            "username": "jane_smith", 
            "email": "[email protected]",
            "active": false
        }
    ],
    "pagination": {
        "page": 1,
        "totalPages": 5,
        "totalUsers": 50
    }
}

🧠 Test Your Knowledge

How do you access the second element in a JSON array?