Home > Net >  When using fetch() in JavaScript how do I render details from the returned object onto the html page
When using fetch() in JavaScript how do I render details from the returned object onto the html page

Time:12-18

I'm using fecth() with JSON to get some details from a 3rd party API. I then want to display these details in my html so they render on the page.

The API I am using returns details about ski resorts, for example, the resort name, weather conditions and other details.

This is my fetch()

async function loadResortName() {
      const response = await fetch('https://api.fnugg.no/search?q=Harpefossen',{
            headers: {
                //'Accept': 'application/json'
            },
            dataType: "json",
      });
      const resortName = await response.json();
        console.log(resortName);
        document.getElementById('test1').innerHTML = resortName.name
      }
      loadResortName();
<div id="test1">
   [resort name should display here]             
</div>

The console.log returns a complex javascript object that seems to contain nested objects and arrays. I need to be able to render in html on the page:

  1. The resort name
  2. the wind name, mps and speed
  3. condition_description
  4. The weather symbol

This is a screen shot from the console of how the object returns. As you can see these details are nested down within the object, but I can't figure out how to access them and render them on the html page, can anyone give me an example of how to do this? with my limited knowledge I thought I'd just be able to do something like resortName.name but this fails.

enter image description here

CodePudding user response:

As you mentioned "https://api.fnugg.no/search?q=Harpefossen" returns more than just the resort name. The response contains all the data that you need.

const resp = await fetch('https://api.fnugg.no/search?q=Harpefossen')
const data = await resp.json()
data.hits.hits[0]._source.name // hotel name
data.hits.hits[0]._source.conditions.current_report // weather report
  • Related