Arrays and Objects

Modern JavaScript

JavaScript Arrays

In programming, arrays are a way to store data in a structured way. We use arrays when we have multiple items (generally of the same type) that we want to store together.

Before we jump into arrays, let's take a minute to get a project setup from scratch.

I will also show you some shortcuts to make your life easier when writing HTML.

Show/Hide Video

Now that our project is setup, let's take a look at arrays:

Show/Hide Video

Here is the code from the video:

const bookTitles = [
    'It Ends With Us',
    'Onyx Storm',
    'Ugly Love',
    'Hopeless',
]

for (let i = 0; i < bookTitles.length; i++) {
    console.log(bookTitles[i])
}

JavaScript Objects

Objects are another way to store data in JavaScript. Objects are used when we have multiple pieces of data that we want to store together.

Show/Hide Video

Here is the code from the video:

const book = {
    title: 'Atomic Habits',
    author: 'James Clear',
    released: '10/16/2018'
}

console.log(`${book.title} was written by ${book.author}`)

Accessing Object Properties

To access the properties of an object, we use dot notation. For example, to access the title property of the book object, we would use book.title.

We can also access object properties using bracket notation. Accessing it this way would look like: book['title']. This is useful when the property name is stored in a variable.

This video explains how to do both:

Show/Hide Video

Here is the code from the video:

const part = 'title' // 'author' // 'released'

console.log(book.title)
console.log(book['title'])
console.log(book[part])

Creating Objects from Existing Variables

If we already have variables that we want to use as properties in an object, we can simplify the process by using object shorthand notation.

This video explains how to do this:

Show/Hide Video

Here is the code from the video:

const title = 'Atomic Habits'
const author = 'James Clear'
const released = '10/16/2018'

const book = { title, author, released }
console.log(book)

Combining Arrays and Objects

We can also combine arrays and objects to create more complex data structures. Take a look:

Show/Hide Video

Here is the code:


// object with an array as a property
const book = {
    title: 'Atomic Habits',
    author: 'James Clear',
    released: '10/16/2018'
    sequels: [
        'Atomic Habits 2',
        'Atomic Behaviors',
        'Atomic Actions'
    ]
}

console.log(book.sequels[1])

// array of objects
const books = [{
    title: 'Atomic Habits',
    author: 'James Clear',
    released: '10/16/2018',
}, {
    title: 'Onyx Storm',
    author: 'Rebecca Yarros',
    released: '9/9/202'
}, {
    title: 'Hopeless',
    author: 'Alison Moore',
    released: '9/9/202'	
}]

console.log(books)

Creating and Appending Elements

Now that we have a good understanding of arrays and objects, let's put that knowledge to use by creating and appending elements to the DOM.

This video will show you how to create a list of books using the data we have stored in an array of objects:

Show/Hide Video

Here is the code from the video:

const books = [{
    title: 'Atomic Habits',
    author: 'James Clear',
    released: '10/16/2018',
}, {
    title: 'Onyx Storm',
    author: 'Rebecca Yarros',
    released: '9/9/202'
}, {
    title: 'Hopeless',
    author: 'Alison Moore',
    released: '9/9/202'	
}]


// this is the ol element in the HTML
const booksList = document.querySelector('#books')

// iterate over the books array
books.forEach(book => {
    const li = document.createElement('li') // create a new li element
    booksList.append(li) // append the li element to the ol element

    const html = `
        <span class="title">${book.title}</span>
        <span class="author">${book.author}</span>
    `

    li.innerHTML = html
})

Object Destructuring

Object destructuring is a way to extract multiple properties from an object and assign them to variables in a single statement.

This video explains how to use object destructuring:

Show/Hide Video

Here is the code from the video:

// Note: book and bookList variables removed for brevity

books.forEach(book => {
    const li = document.createElement('li')
    booksList.append(li)

    const { title, author, released } = book // object destructuring

    const html = `
        <span class="title">${title}</span>
        <span class="author">${author}</span>
        <span class="released">${released}</span>
    `

    li.innerHTML = html
})

Exercise 1

Show/Hide Video

In this exercise, I want you to modify the project that we have been working on. You will add a 'genres' property to each book. Each book must have at least two genres. You don't need to use the "real" genres, just make them up.

Additionally, you can use this stylesheet to make your page look better.

Here are some common book genres to get you started:

  • Fiction
  • Non-Fiction
  • Fantasy
  • Mystery
  • Science Fiction
  • Romance
  • Thriller
  • Historical Fiction

Hints

How do I create a new property in an object?

You can create a new property in an object by bracket notation. For example:

const book = {
    title: 'Atomic Habits',
    genres: [ 'Self-Help', 'Non-Fiction' ]
}

Solution

Show Solution

Note

Remember that you might have chosen different genres for your books. The solution below is just an example.

const books = [{
    title: 'Atomic Habits',
    author: 'James Clear',
    released: '10/16/2018',
    genres: [ 'Self-Help', 'Non-Fiction' ]
}, {
    title: 'Onyx Storm',
    author: 'Rebecca Yarros',
    released: '9/9/202',
    genres: [ 'Romance', 'Fiction', 'Fantasy' ]
}, {
    title: 'Hopeless',
    author: 'Alison Moore',
    released: '9/9/202',
    genres: [ 'Mystery', 'Thriller' ]
}]
Walkthrough Video

Exercise 2

Show/Hide Video

For this exercise, I want you to modify the project again. Now you will get the genres from each book and display them in the list of books.

You will need to add a ul element to each li element that will contain the genres. You can use the following HTML structure:


<li>
    <span class="title">Atomic Habits</span>
    <span class="author">James Clear</span>
    <span class="released">10/16/2018</span>
    <ul>
        <li>Self-Help</li>
        <li>Non-Fiction</li>
    </ul>
</li>

Note

You can add the ul element to the html variable that you are creating in the forEach loop. You cannot add the li elements because each book could have a different number of genres.

Hints

How do I add the 'ul' element?

You can simply add it to the html variable that you are creating in the forEach loop:

    const html = `
        <span class="title">${title}</span>
        <span class="author">${author}</span>
        <span class="released">${released}</span>
        <ul class="genres"></ul> // here's where the genre li's will go
    `
How do I add the 'li' elements to the 'ul' element?

You will first have to get the ul element from the li element. You can do this by using the querySelector method:

const ul = li.querySelector('.genres')

Then you can iterate over the genres array and create a new li element for each genre:

genres.forEach(genre => {
    const genreLi = document.createElement('li')
    genreLi.textContent = genre
    ul.append(genreLi)
})

Solution

Show Solution
const booksList = document.querySelector('#books')

books.forEach(book => {
    const li = document.createElement('li')
    booksList.append(li)

    const { title, author, released, genres } = book

    li.innerHTML = `
        <span class="title">${title}</span>
        <span class="author">${author}</span>
        <span class="released">${released}</span>
        <ul class="genres"></ul>
    `

    const ul = li.querySelector('ul')
    genres.forEach(genre => {
        const genreLi = document.createElement('li')
        ul.append(genreLi)
        genreLi.textContent = genre
    })
})
Walkthrough Video

Object Entries, Values, and Keys

Sometimes when we have an object, we want to get an array of its properties, values, or keys. There are three methods that we can use to do this:

  • Object.entries(): Returns an array of a given object's own enumerable string-keyed property [key, value] pairs.

  • Object.values(): Returns an array of a given object's own enumerable property values.

  • Object.keys(): Returns an array of a given object's own enumerable property names.

This video shows how to use these methods:

Show/Hide Video

Here is the code from the video:

const [ firstBook ] = books // get the first book in the array

//console.log(firstBook)
console.log(Object.values(firstBook))
console.log(Object.keys(firstBook))
console.log(Object.entries(firstBook))