Home > Mobile >  Name of countries are not displaying
Name of countries are not displaying

Time:10-25

Why it displays [object Object]? I'm trying to display a selection of countries. See the example code.

enter image description here

document.addEventListener('DOMContentLoaded', () =>{

  const selectDrop = document.querySelector('#countries');
 
  
  fetch('https://restcountries.com/v3.1/all').then(res => {
    return res.json();
  }).then(data => {
      let output = "";
    data.forEach(country => {

      output  = `<option>${country.name}</option>`;
    })
    selectDrop.innerHTML = output;
  }).catch(err => {
    console.log(err);
  })
  
  });

CodePudding user response:

it should be country.name.common

country.name is an object

document.addEventListener('DOMContentLoaded', () =>{

  const selectDrop = document.querySelector('#countries');
 
  
  fetch('https://restcountries.com/v3.1/all').then(res => {
    return res.json();
  }).then(data => {
      const output = data.map(d => d.name.common)
                         .sort()
                         .map(name => `<option>${name}</option>`)
                         .join('')
    selectDrop.innerHTML = output;
  }).catch(err => {
    console.log(err);
  })
  
  });
<select id="countries"></select>

I edited the code to add sort

CodePudding user response:

I have seen your data and it structure is something like this:

"name":{
  "common":"Bulgaria",
  "official":"Republic of Bulgaria",
  ...
}

You need to access the property like country.name.common

  • Related