Lesson 7: Combining Arrays and Objects

Lesson Goal:

Learn how to combine arrays and objects to create more complex and realistic data structures, such as arrays of objects and objects with nested arrays or objects.


Why Combine Arrays and Objects?

Real-world data is often more complex than flat lists or simple objects. For example:

  • A list of users → Array of user objects
  • A shopping cart → Array of product objects
  • A student record → Object with nested arrays (e.g. grades, attendance)

Common Structures

1. Array of Objects

Used when you have multiple items, each with multiple attributes.

let users = [
  { name: "Anna", age: 25 },
  { name: "Ben", age: 28 },
  { name: "Cara", age: 22 }
];

You can access an individual object using array indexing:

console.log(users[0].name);  // Output: Anna

Loop through to access each property:

for (let user of users) {
  console.log(user.name + " is " + user.age + " years old.");
}

2. Object with Arrays

Used when an entity has multiple values for a single key.

let student = {
  name: "Leo",
  grades: [85, 90, 78]
};

console.log(student.grades[1]);  // Output: 90

You can loop through the grades:

for (let grade of student.grades) {
  console.log("Grade:", grade);
}

3. Nested Objects

You can also place objects inside objects to represent deeply structured data.

let person = {
  name: "Sam",
  contact: {
    email: "sam@mail.com",
    phone: "123-456"
  }
};

console.log(person.contact.email);  // Output: sam@mail.com

Try It Yourself

let products = [
  { id: 1, name: "Pen", price: 1.5 },
  { id: 2, name: "Notebook", price: 3.0 }
];

// Access the price of the second product
console.log(products[1].price);  // Output: 3.0

// Add a new property to the first product
products[0].inStock = true;
console.log(products[0]);

Tips

  • Use loops (for, for...of, or forEach) to process arrays of objects
  • Chain property access carefully: users[0].address.city
  • When working with deeply nested data, consider checking if each level exists before accessing it (to avoid undefined errors)