By the end of this lesson, you will be able to work effectively with arrays of objects in JavaScript.
Arrays of objects are a way to store multiple related items in JavaScript. Imagine you have a list of students. Each student has properties like name, age, and grade. Instead of storing each property separately, you can create an array of student objects.
Think about a shopping list. You might want to store different products, each with a name, price, and quantity. An array of objects allows you to keep this information organized.
File: students.js
const students = [
{ name: 'Alice', age: 20, grade: 'A' },
{ name: 'Bob', age: 22, grade: 'B' },
{ name: 'Charlie', age: 21, grade: 'C' }
];
students.forEach(student => {
console.log(`${student.name} is ${student.age} years old and has a grade of ${student.grade}.`);
});
Alice is 20 years old and has a grade of A.
Bob is 22 years old and has a grade of B.
Charlie is 21 years old and has a grade of C.
The code above creates an array called students. Each student is an object with properties: name, age, and grade. The forEach method loops through each student and prints their details. This approach keeps your data organized and easier to manage.
Create an array of books. Each book should have a title, author, and year published. Write a program to log each book’s details in the format: “
const books = [
{ title: '1984', author: 'George Orwell', year: 1949 },
{ title: 'To Kill a Mockingbird', author: 'Harper Lee', year: 1960 },
{ title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', year: 1925 }
];
books.forEach(book => {
console.log(`${book.title} by ${book.author}, published in ${book.year}.`);
});
forEach for iteration or others like map if needed.forEach.Further reading: developer.mozilla.org