🍌Arrays of objects

An array is a collection of values that can be of any data type, including objects. An array of objects is an array that contains objects as its elements.

Here is an example of an array of objects:

const players = [
  {
    name: 'John',
    score: 100
  },
  {
    name: 'Jane',
    score: 120
  },
  {
    name: 'Bob',
    score: 90
  }
];

In this example, the players array contains three objects, each representing a player in a game. Each object has two properties: name and score.

You can access the individual objects in the array using index notation, just like you would with any other array. For example, to access the second object (Jane), you can use the following code:

console.log(players[1]); // Output: { name: 'Jane', score: 120 }

You can also access the properties of the objects using dot notation or bracket notation. For example:

console.log(players[0].name); // Output: John
console.log(players[1]['score']); // Output: 120

You can also use array methods, such as forEach() or map(), to iterate over the array of objects and perform operations on the objects

players.forEach(player => {
  console.log(`${player.name} has a score of ${player.score}`);
});

// Output:
// John has a score of 100
// Jane has a score of 120
// Bob has a score of 90
const scores = players.map(player => player.score);
console.log(scores); // Output: [100, 120, 90]

Last updated