Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I can't figure out how to display this data in a separate line in my html from JS

  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 class="justify-center flex">Results</h2>
<ul id="result-list">
  <li class="list-item "></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.
This is how it displays on the webpage
I want it to display as it looks in the console log

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading