Home > Software engineering >  I'm trying to create a table which shows the details of countries from the restcountries api. I
I'm trying to create a table which shows the details of countries from the restcountries api. I

Time:08-13

I want to show each country details like this.

I tried to loop but all the contents are merged in a single cell. What can be done in order to get the result??

enter image description here

const sNo = document.querySelector(".sno");
const country = document.querySelector(".country");
const capital = document.querySelector(".capital");
const currency = document.querySelector(".currency");
const population = document.querySelector(".population");
const flag = document.querySelector(".flag");


const tableBody = document.querySelector(".table_body");

const countryList = async function(url) {
  const response = await fetch(url);
  const data = await response.json();
  console.log(data);
  for (let i = 0; i < data.length; i  ) {

    sNo.textContent  = i   1   "\n";
    country.textContent  = data[i].name.common;
    capital.textContent  = data[i].capital
  }
};
countryList("https://restcountries.com/v3.1/all");

CodePudding user response:

I suggest you use map and template literals

Note i 1 "\n"; would never work and no need for a newline in HTML you would need (i 1) to concatenate a number to a string after incrementing

Also filter your fields

https://restcountries.com/v2/all?fields=name,capital,currencies,flag,population
If you do ,flag you need country.flag instead of country.flags.svg

Here is a filtered version using https://restcountries.com/v2/all?fields=name,capital,currencies,flag,population

tableBody.innerHTML = data
 .map((country, i) => {
   return `<tr><td>${i 1}</td>
   <td>${country.name}</td>
   <td>${country.capital || "-"}</td>
   <td>${country.currencies ? Object.values(country.currencies)[0].symbol : "-" }</td>
   <td>${country.population}</td>
   <td><img src="${country.flag}" /></td></tr>`;
   }).join(""); 

And another with fetch

https://jsfiddle.net/mplungjan/d7vxpg8m/

const tableBody = document.querySelector("table tbody");


const countryList = async function(url) {
  const response = await fetch(url);
  const data = await response.json();
  tableBody.innerHTML = data.map((country, i) => {
  const currencies = country.currencies || {};
  const currency =  Object.values(country.currencies)
  const symbol = currency.length > 0 ? currency[0].symbol : "-"
    return `<tr>
  <td>${i   1}</td>
  <td>${country.name.common}</td>
  <td>${country.capital || "-"}</td>
  <td>${symbol}</td>
  <td>${country.population}</td>
  <td>${country.flag}</td>
  </tr>`
  }).join("")
}
countryList("https://restcountries.com/v3.1/all?fields=name,capital,currencies,population,flag")

And here is the original answer

const tableBody = document.querySelector("table tbody");

tableBody.innerHTML = data
 .map((country, i) => `<tr><td>${i 1}</td>
   <td>${country.name.common}</td>
   <td>${country.capital || "-"}</td>
   <td>${country.currencies ? Object.values(country.currencies)[0].symbol : "-" }</td>
   <td>${country.population}</td>
   <td><img src="${country.flags.svg}" /></td></tr>`).join(""); // and so on
img { height: 50px; }
td { text-align:center;}
<table>
  <thead>
    <tr>
      <th>S.No</th>
      <th>Country</th>
      <th>Capitol</th>
      <th>Currency</th>
      <th>Population</th>
      <th>Flag</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>




<!-- testdata -->


<script>
const data = [{"name":{"common":"Kuwait","official":"State of Kuwait","nativeName":{"ara":{"official":"دولة الكويت","common":"الكويت"}}},"tld":[".kw"],"cca2":"KW","ccn3":"414","cca3":"KWT","cioc":"KUW","independent":true,"status":"officially-assigned","unMember":true,"currencies":{"KWD":{"name":"Kuwaiti dinar","symbol":"د.ك"}},"idd":{"root":" 9","suffixes":["65"]},"capital":["Kuwait City"],"altSpellings":["KW","State of Kuwait","Dawlat al-Kuwait"],"region":"Asia","subregion":"Western Asia","languages":{"ara":"Arabic"},"translations":{"ara":{"official":"دولة الكويت","common":"الكويت"},"ces":{"official":"Stát Kuvajt","common":"Kuvajt"},"cym":{"official":"State of Kuwait","common":"Kuwait"},"deu":{"official":"Staat Kuwait","common":"Kuwait"},"est":{"official":"Kuveidi Riik","common":"Kuveit"},"fin":{"official":"Kuwaitin valtio","common":"Kuwait"},"fra":{"official":"État du Koweït","common":"Koweït"},"hrv":{"official":"Država Kuvajt","common":"Kuvajt"},"hun":{"official":"Kuvaiti Állam","common":"Kuvait"},"ita":{"official":"Stato del Kuwait","common":"Kuwait"},"jpn":{"official":"クウェート国","common":"クウェート"},"kor":{"official":"쿠웨이트국","common":"쿠웨이트"},"nld":{"official":"Staat Koeweit","common":"Koeweit"},"per":{"official":"دولت کویت","common":"کُویت"},"pol":{"official":"Państwo Kuwejt","common":"Kuwejt"},"por":{"official":"Estado do Kuwait","common":"Kuwait"},"rus":{"official":"Государство Кувейт","common":"Кувейт"},"slk":{"official":"Kuvajtský štát","common":"Kuvajt"},"spa":{"official":"Estado de Kuwait","common":"Kuwait"},"swe":{"official":"Staten Kuwait","common":"Kuwait"},"urd":{"official":"دولتِ کویت","common":"کویت"},"zho":{"official":"科威特国","common":"科威特"}},"latlng":[29.5,45.75],"landlocked":false,"borders":["IRQ","SAU"],"area":17818.0,"demonyms":{"eng":{"f":"Kuwaiti","m":"Kuwaiti"},"fra":{"f":"Koweïtienne","m":"Koweïtien"}},"flag":"\uD83C\uDDF0\uD83C\uDDFC","maps":{"googleMaps":"https://goo.gl/maps/aqr3aNQjS1BAvksJ7","openStreetMaps":"https://www.openstreetmap.org/relation/305099"},"population":4270563,"fifa":"KUW","car":{"signs":["KWT"],"side":"right"},"timezones":["UTC 03:00"],"continents":["Asia"],"flags":{"png":"https://flagcdn.com/w320/kw.png","svg":"https://flagcdn.com/kw.svg"},"coatOfArms":{"png":"https://mainfacts.com/media/images/coats_of_arms/kw.png","svg":"https://mainfacts.com/media/images/coats_of_arms/kw.svg"},"startOfWeek":"sunday","capitalInfo":{"latlng":[29.37,47.97]},"postalCode":{"format":"#####","regex":"^(\\d{5})$"}}];</script>

  • Related