Arrays of Objects

Now you can put arrays and objects together. An array of objects holds one object per record. Most real data looks like this: a list of contacts, products or messages.

const team = [
  { name: "Alice", dept: "HR" },
  { name: "Bob", dept: "IT" },
  { name: "Emma", dept: "IT" },
];
console.log(team[1].name);
console.log(team.length);

Output:

Bob
3

Think of it as a table. The array is the table, each object is a row, and the keys are the columns. Read team[1].name from left to right: take item 1 of the array (Bob's object), then read its name.

All the array methods you learned still work. The only difference is that the callback now gets a whole object, so it reads a property from it:

<!-- continues -->
console.log(team.map(person => person.name));
console.log(team.find(person => person.name === "Bob"));

Output:

[ 'Alice', 'Bob', 'Emma' ]
{ name: 'Bob', dept: 'IT' }

map takes one column out of the table. find gives back the first row that matches. To keep only some rows, use filter, and then forEach to print each one:

<!-- continues -->
const inIT = team.filter(person => person.dept === "IT");
inIT.forEach(person => console.log(person.name));

Output:

Bob
Emma

Give the callback parameter a name that describes one record, like person or order. Then the code reads almost like a sentence.

Remember that find gives undefined when nothing matches. If you read a property from that result, use ?. so the program does not crash:

<!-- continues -->
const zara = team.find(person => person.name === "Zara");
console.log(zara?.dept);

Output:

undefined

In the exercise, filter a team by a department from the input, and print the names you find.