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.
Real-world data is often more complex than flat lists or simple objects. For example:
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.");
}
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);
}
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
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]);
for
, for...of
, or forEach
) to process arrays of objectsusers[0].address.city
undefined
errors)