AI Hints
Home›JavaScript Tutorial›Working with Objects
JavaScript · Lesson 63 of 138

Arrays of Objects

Real data.

⏱ 2 min read▶ Video at 1:17:07🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Real data is usually an array of objects. A list of users, products, or orders, where each one is an object with the same keys. Everything you've learned about arrays and objects comes together here.

Arrays of Objects
From the video: Arrays of Objects
  • Real data
  • A list of objects
  • Everything together

Querying a list

Here are four books. Filter finds the ones published after two thousand. Map pulls out just the titles. Find looks up one book by its author. And to sorted orders them by rating, highest first. Run it.

app.jsjavascript
const books = [
  { title: "Dune", author: "Herbert", year: 1965, rating: 4.3 },
  { title: "The Road", author: "McCarthy", year: 2006, rating: 4.0 },
  { title: "Circe", author: "Miller", year: 2018, rating: 4.3 },
  { title: "Emma", author: "Austen", year: 1815, rating: 4.0 },
];

console.log(books.filter(b => b.year > 2000).map(b => b.title));
console.log(books.find(b => b.author === "Austen").title);
console.log(books.toSorted((a, b) => b.rating - a.rating).map(b => b.title));
Output
[ 'The Road', 'Circe' ]
Emma
[ 'Dune', 'Circe', 'The Road', 'Emma' ]

Like a tiny database

An array of objects is like a tiny database table. Each object is a row, and each key is a column. Filter is like a where clause, map picks columns, and sort orders the rows. When data comes from a web server, it almost always arrives in this shape.

keyvalue
Arraythe table
Objecta row
Keya column
filter / map / sortquery it

Summary

Arrays of objects are how real data looks, and array methods let you query them like a database. Next, JSON, data as text.

Key takeaways
  • Array of objects
  • filter, map, find
  • Sort by a key
Next up: JSON — data as text