I am trying to dynamically add objects from a json file to my HTML file. For some reason, when looping through the fetched json file, the properties of objects are undefined. Logging the entire json file into console works, the problem appears looping through the file for some reason. I have double checked, the title and body properties do exist for the json objects.
Here’s the Javascript file:
window.onload = function() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then(json => {
console.log(json); // console output shows the objects fine
for (post in json) {
console.log(post.title);
var div = document.createElement('div');
var title = document.createElement('h1');
var body = document.createElement('p');
title.innerText = post.title;
body.innerText = post.body;
div.appendChild(title);
div.appendChild(body);
document.body.appendChild(div);
}
})
}
Here’s the HTML file:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="src/js/script.js"></script>
<link rel="stylesheet" type="text/css" href="res/css/style.css">
<title>Lecture 7 - JS-4</title>
</head>
<body>
<h1> Fetch API</h1>
</body>
</html>
This is what the page looks like:
I have searched online and in most cases, the problem seems to be that the function fetching the data does not return anything. However, as I am not asking for the value of the function, this doesn’t appear to be the problem in my case.
2
Answers
the for loop is wrong
try
instead of
the
for..of
loop iterates over values while thefor..in
loop iterates over indices (for some strange legacy reasons)also don’t forget
const
orlet
since you introduce a new variable/constant calledpost
inside the loopUse
of
instead ofin