Arrays of Objects
A pet shop has more than one animal. When you have many objects of the same kind, put them in an array. Arrays of objects are among the most common things in programming: products in an online shop, messages in a chat or books in a library are all stored this way.
const pets = [
{ name: "Rex", species: "dog", age: 3 },
{ name: "Bella", species: "cat", age: 2 },
{ name: "Kiwi", species: "parrot", age: 4 }
];
console.log(pets);[{ name: "Rex", species: "dog", age: 3 }, { name: "Bella", species: "cat", age: 2 }, { name: "Kiwi", species: "parrot", age: 4 }]Each element of the array is one object, and the objects are separated by commas like any other elements. To get to a property of one pet, first pick the element by its index, then the property with a dot:
console.log(pets[1]);
console.log(pets[1].name);{ name: "Bella", species: "cat", age: 2 }
BellaRead pets[1].name from left to right: from pets, take the element at index 1 (Bella's object), and from it the property name.
Everything you know about arrays and objects still works. pets.length is the number of pets, push() adds a new pet at the end, and you can change a property of one pet:
pets.push({ name: "Coco", species: "rabbit", age: 1 });
pets[0].age = 4;
console.log(pets.length);
console.log(pets[0]);4
{ name: "Rex", species: "dog", age: 4 }Typical mistakes:
pets.namegivesundefined. The array itself has no name, only the pets in it do. Pick a pet first:pets[0].name.- An index that isn't in the array, for example
pets[10].name.pets[10]isundefined, andundefinedhas no properties, so the program ends withTypeError: Cannot read properties of undefined (reading 'name').
Instructions
Print the species of the third pet, Kiwi. The console should show parrot.
A rabbit has arrived. Add it to the end of the array with push(): { name: "Coco", species: "rabbit", age: 1 }.
Print the whole array pets. Coco should now be at the end.
Start programming for free
5/9