02-Working with JSON
Last updated
Last updated
In this module, we'll start to store and use the JSON data.
With the JSON, we can drill down into the layers of data with the dot operator.
Notice that when we run the app now, we are deeper into the JSON object, deeper into the data:
If we can drill down, we can store that specific data in a variable. Let's do that:
If you run the app at this point, you should get the same results in the console:
Let's get to the point where we start to show results. We want to write an if-else
statement that will deal with the data using the following logic:
if
Let's start by stubbing out the if
. Notice that we have taken out the console.log(articles)
:
Keeping it simple with this basic console.log
will allow us to handle the logic of having no results. This is a common trick to keep momentum. We don't need to get down in the weeds of what is going to happen if there are no results at this moment. We can handle it later. The console statement is a sort of placeholder for now.
else
Now let's handle the else
. The articles
variable contains an array of articles, so we can iterate over that array in the else:
Here we write a for loop
that will iterate for the length of the articles
array. The first set of results holds an array of 10 items(0-9), and we are simply printing out a number for each item in the index:
Again, keeping simple console.log
s will help us make sure that we are on the right track as we move through the build.
Now that we are sure we are iterating over the articles properly, we can turn to doing DOM manipulation each time we iterate through the results. Add the following code:
Here's what we're doing each time the for loop runs: 1. We create an article variable that will create a node in the DOM that is an article
element. Remember that article
is an HTML5 element. 2. We also create a heading variable that creates a node in the DOM that is an h2
element. 3. We call appendChild() on the article element. This will create a child node on that element. We pass in heading
to the appendChild method. This means that there will be an h2
element created inside each article
element. 4. Since we have a section
in our original html
file, we call the appendChild() method on the section
element. We pass in the article
to that. This way, the article is a child of section
, and the h2
is a grandchild of section
.
You should get the following result:
Take a look at the Elements tab in Chrome Tools to see how this appended to the DOM:
We don't have any actual data showing up, but we have our containers. Let's get the actual data in the next section.