Loops, and where your data lives

INPUT · Slides

Putting objects in an array

01 / 04

When there are more of the same shape

For one book, one object called book is fine. But what about three?

Adding variables book1 book2 book3 is the same pain as before you learned arrays. And when things of the same shape line up, that is an array.

02 / 04

Put an object in an item

Array items are not only numbers and strings. An object can be an item just as it is.

So you end up with { } lined up inside [ ]. It is normal to put each one on its own line so it reads well.

const books = [  { title: "Sky Book", price: 800 },  { title: "Sea Book", price: 1200 },];console.log(books[0].title);

Result

Sky Book

03 / 04

Take it out in two steps

books[0].title looks hard taken all at once, but split into two steps it is easy.

  • books[0] … take the first item out of the array. What is inside is an object
  • .title … take the title out of that object

You are just following it left to right. Trace it with your finger until it settles.

const books = [  { title: "Sky Book", price: 800 },  { title: "Sea Book", price: 1200 },];const second = books[1];console.log(second.title);console.log(books[1].price);

Result

Sea Book
1200

04 / 04

Changing it takes the same shape

If you can take it out, you can change it. Put it on the left, as in books[0].price = 900;.

That is arrays, objects and nesting all in hand. Next let us put a loop through the lot.

const books = [  { title: "Sky Book", price: 800 },];books[0].price = 900;console.log(books[0].price);

Result

900