document.querySelector("#enter").addEventListener("click", e => {
e.preventDefault();
var inputValue = searchApi.value;
fetch('https://wft-geo-db.p.rapidapi.com/v1/geo/cities/' inputValue, options)
.then(response => response.json())
.then(response => {
console.log(response);
return response;
})
.then((data) => {
var title = document.createElement("li")
title.classList.add('list-item');
title.innerText = JSON.stringify(data);
var list = document.getElementById("result-list");
list.appendChild(title);
})
.catch(err => console.error(err));
});
HTML looks like this
<h2 >Results</h2>
<ul id="result-list">
<li ></li>
</ul>
Because I use JSON stringify it turns out as it did, but I want the data to be displayed one by one and not all in one line. I have tried forEach, and for loop but I don't think I did it correctly, so any help is appreciated.
CodePudding user response:
Your data is not an array, it is a plain object-- as such, you cannot simply loop over it by index like you would an array or other iterable. If you want to get all key/value pair entries from this object into an array to iterate you can use Object.entries
:
.then((data) => {
const myData = data.data;
Object.entries(myData).forEach(([key, val]) => {
var title = document.createElement("li")
title.classList.add("list-item");
title.innerText = `${key}: ${val}`;
var list = document.getElementById("result-list");
list.appendChild(title);
});
})
Note that this will probably come back in alphabetical order-- if you want a specific order, you would need to adjust your approach. You can also use the Object.entries
approach for other solutions listed in your original question on this topic.