Since an array can contain any values, we can create an array of objects:
const person1 = { name: 'John' };
const person2 = { name: 'Julia' };
const person3 = { name: 'James' };
const people = [person1, person2, person3];
console.log(people);
We can also define an array of objects in a single statement:
const people = [
{ name: 'John' },
{ name: 'Julia' },
{ name: 'James' },
];
console.log(people);
Accessing object properties
Accessing the properties of each object is simple.
First we need to use bracket notation to access the object by its index.
We can then access the object's properties as usual:
const people = [
{ name: 'John' },
{ name: 'Julia' },
{ name: 'James' },
];
// one way
const person1 = people[0];
console.log(person1.name):
// another way
const person1name = people[0].name;
console.log(person1name);
Iterating the objects
Iterating through an array of objects is also simple:
const people = [
{ name: 'John' },
{ name: 'Julia' },
{ name: 'James' },
];
for (let i = 0; i < people.length; i++) {
const person = people[i];
console.log(person.name);
}
It helps to assign the individual object to its own variable at the beginning of the loop.
In this case, people[i]
gets assigned to person
to make the current object easier to work with.