最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - REST Countries API how to get content - Stack Overflow

programmeradmin3浏览0评论

So I am trying to use REST country API to get information about China, I have looked at a couple of sources to get an idea of how to get all the countries. But I am stuck on how to get just china's any idea how I can change my code so it is just China's (I am trying to get the 'Capital' 'dialing-code' 'population' 'currencies' 'region' thx!!

// Global Variables
const countriesList = document.getElementById("countries");
let countries; // will contain "fetched" data

// Event Listeners
// countriesList.addEventListener("change", event => displayCountryInfo(event.target.value));

countriesList.addEventListener("change", newCountrySelection);

function newCountrySelection(event) {
  displayCountryInfo(event.target.value);
}

// fetch("")
// .then(function(res){
//   // console.log(res);
//   return res.json();
// })
// .then(function(data){
//   // console.log(data);
//   initialize(data);
// })
// .catch(function(err){
//   console.log("Error:", err);
// });

fetch("")
.then(res => res.json())
.then(data => initialize(data))
.catch(err => console.log("Error:", err));

function initialize(countriesData) {
  countries = countriesData;
  let options = "";
  // for(let i=0; i<countries.length; i++) {
  //   options += `<option value="${countries[i].alpha3Code}">${countries[i].name}</option>`;
  //   // options += `<option value="${countries[i].alpha3Code}">${countries[i].name} (+${countries[i].callingCodes[0]})</option>`;
  // }
  countries.forEach(country => options+=`<option value="${country.alpha3Code}">${country.name}</option>`);
  // document.getElementById("countries").innerHTML = options;
  // document.querySelector("#countries").innerHTML = options;
  countriesList.innerHTML = options;
  // console.log(countriesList);
  // console.log(countriesList.value);
  // console.log(countriesList.length);
  // console.log(countriesList.selectedIndex);
  // console.log(countriesList[10]);
  // console.log(countriesList[10].value);
  // console.log(countriesList[10].text);
  countriesList.selectedIndex = Math.floor(Math.random()*countriesList.length);
  displayCountryInfo(countriesList[countriesList.selectedIndex].value);
}

function displayCountryInfo(countryByAlpha3Code) {
  const countryData = countries.find(country => country.alpha3Code === countryByAlpha3Code);
  document.querySelector("#flag-container img").src = countryData.flag;
  document.querySelector("#flag-container img").alt = `Flag of ${countryData.name}`;  
  document.getElementById("capital").innerHTML = countryData.capital;
  document.getElementById("dialing-code").innerHTML = `+${countryData.callingCodes[0]}`;
  document.getElementById("population").innerHTML = countryData.population.toLocaleString("en-US");
  document.getElementById("currencies").innerHTML = countryData.currencies.filter(c => c.name).map(c => `${c.name} (${c.code})`).join(", ");
  document.getElementById("region").innerHTML = countryData.region;
}
      <div class="row">
        <div class="col-6"><img src="" alt=""></div>
        <div id="countries" class="col-6">
          <div><p>Capital:<span id="capital"></span></p></div>
          <div><p>dialing Code:<span id="dialing-code"></span></p></div>
          <div><p>Population:<span id="population"></span></p></div>
          <div><p>Currencies:<span id="currencies"></span></p></div>
          <div><p>Region:<span id="region"></span></p></div>
        </div>
      </div>

So I am trying to use REST country API to get information about China, I have looked at a couple of sources to get an idea of how to get all the countries. But I am stuck on how to get just china's any idea how I can change my code so it is just China's (I am trying to get the 'Capital' 'dialing-code' 'population' 'currencies' 'region' thx!!

// Global Variables
const countriesList = document.getElementById("countries");
let countries; // will contain "fetched" data

// Event Listeners
// countriesList.addEventListener("change", event => displayCountryInfo(event.target.value));

countriesList.addEventListener("change", newCountrySelection);

function newCountrySelection(event) {
  displayCountryInfo(event.target.value);
}

// fetch("https://restcountries.eu/rest/v2/all")
// .then(function(res){
//   // console.log(res);
//   return res.json();
// })
// .then(function(data){
//   // console.log(data);
//   initialize(data);
// })
// .catch(function(err){
//   console.log("Error:", err);
// });

fetch("https://restcountries.eu/rest/v2/name/china")
.then(res => res.json())
.then(data => initialize(data))
.catch(err => console.log("Error:", err));

function initialize(countriesData) {
  countries = countriesData;
  let options = "";
  // for(let i=0; i<countries.length; i++) {
  //   options += `<option value="${countries[i].alpha3Code}">${countries[i].name}</option>`;
  //   // options += `<option value="${countries[i].alpha3Code}">${countries[i].name} (+${countries[i].callingCodes[0]})</option>`;
  // }
  countries.forEach(country => options+=`<option value="${country.alpha3Code}">${country.name}</option>`);
  // document.getElementById("countries").innerHTML = options;
  // document.querySelector("#countries").innerHTML = options;
  countriesList.innerHTML = options;
  // console.log(countriesList);
  // console.log(countriesList.value);
  // console.log(countriesList.length);
  // console.log(countriesList.selectedIndex);
  // console.log(countriesList[10]);
  // console.log(countriesList[10].value);
  // console.log(countriesList[10].text);
  countriesList.selectedIndex = Math.floor(Math.random()*countriesList.length);
  displayCountryInfo(countriesList[countriesList.selectedIndex].value);
}

function displayCountryInfo(countryByAlpha3Code) {
  const countryData = countries.find(country => country.alpha3Code === countryByAlpha3Code);
  document.querySelector("#flag-container img").src = countryData.flag;
  document.querySelector("#flag-container img").alt = `Flag of ${countryData.name}`;  
  document.getElementById("capital").innerHTML = countryData.capital;
  document.getElementById("dialing-code").innerHTML = `+${countryData.callingCodes[0]}`;
  document.getElementById("population").innerHTML = countryData.population.toLocaleString("en-US");
  document.getElementById("currencies").innerHTML = countryData.currencies.filter(c => c.name).map(c => `${c.name} (${c.code})`).join(", ");
  document.getElementById("region").innerHTML = countryData.region;
}
      <div class="row">
        <div class="col-6"><img src="" alt=""></div>
        <div id="countries" class="col-6">
          <div><p>Capital:<span id="capital"></span></p></div>
          <div><p>dialing Code:<span id="dialing-code"></span></p></div>
          <div><p>Population:<span id="population"></span></p></div>
          <div><p>Currencies:<span id="currencies"></span></p></div>
          <div><p>Region:<span id="region"></span></p></div>
        </div>
      </div>

Share Improve this question asked Dec 7, 2020 at 21:27 JackJack 491 gold badge2 silver badges9 bronze badges 3
  • Can you narrow the problem down? What part of this code is going wrong? – tadman Commented Dec 7, 2020 at 21:29
  • It's not clear what you want to achieve. More information please. The code you posted looks ok - it fetches data for China, including mainland and territories (Macao, Taiwan). What do you need help with? – Andrey Commented Dec 7, 2020 at 21:36
  • I think you have your answer below, but next please try to tidy up your code before asking the munity for help. Just makes it a more pleasant experience that's all. Thank you. – codemonkey Commented Dec 7, 2020 at 21:45
Add a ment  | 

2 Answers 2

Reset to default 1

If you use GET https://restcountries.eu/rest/v2/alpha/cn (Code endpoint), you can get information for only China. Then, all you need is to extract the right props, optionally using object destructuring. For example:

fetch('https://restcountries.eu/rest/v2/alpha/cn')
  .then(res => res.json())
  .then(data => initialize(data))
  .catch(err => console.log('Error:', err.message)); // (I fixed this)

// A little destructuring...
function initialize({
  name,
  capital,
  callingCodes,
  population,
  currencies,
  region
}) {
  console.log({
    name,
    capital,
    callingCodes,
    population,
    currencies,
    region
  })
}

This code will send only the data for China into your initialize function. The trick is this part:

data.filter(item => item.name === 'China')

I assume you can rewrite the initialize function to process the data correctly.

// Global Variables
const countriesList = document.getElementById("countries");
let countries; // will contain "fetched" data

// Event Listeners
// countriesList.addEventListener("change", event => displayCountryInfo(event.target.value));

countriesList.addEventListener("change", newCountrySelection);

function newCountrySelection(event) {
  displayCountryInfo(event.target.value);
}

// fetch("https://restcountries.eu/rest/v2/all")
// .then(function(res){
//   // console.log(res);
//   return res.json();
// })
// .then(function(data){
//   // console.log(data);
//   initialize(data);
// })
// .catch(function(err){
//   console.log("Error:", err);
// });

fetch("https://restcountries.eu/rest/v2/name/china")
.then(res => res.json())
.then(data => initialize(data.filter(item => item.name === 'China')))
.catch(err => console.log("Error:", err));

function initialize(countriesData) {
  console.log(countriesData)
  countries = countriesData;
  let options = "";
  // for(let i=0; i<countries.length; i++) {
  //   options += `<option value="${countries[i].alpha3Code}">${countries[i].name}</option>`;
  //   // options += `<option value="${countries[i].alpha3Code}">${countries[i].name} (+${countries[i].callingCodes[0]})</option>`;
  // }
  countries.forEach(country => options+=`<option value="${country.alpha3Code}">${country.name}</option>`);
  // document.getElementById("countries").innerHTML = options;
  // document.querySelector("#countries").innerHTML = options;
  countriesList.innerHTML = options;
  // console.log(countriesList);
  // console.log(countriesList.value);
  // console.log(countriesList.length);
  // console.log(countriesList.selectedIndex);
  // console.log(countriesList[10]);
  // console.log(countriesList[10].value);
  // console.log(countriesList[10].text);
  countriesList.selectedIndex = Math.floor(Math.random()*countriesList.length);
  displayCountryInfo(countriesList[countriesList.selectedIndex].value);
}

function displayCountryInfo(countryByAlpha3Code) {
  const countryData = countries.find(country => country.alpha3Code === countryByAlpha3Code);
  document.querySelector("#flag-container img").src = countryData.flag;
  document.querySelector("#flag-container img").alt = `Flag of ${countryData.name}`;  
  document.getElementById("capital").innerHTML = countryData.capital;
  document.getElementById("dialing-code").innerHTML = `+${countryData.callingCodes[0]}`;
  document.getElementById("population").innerHTML = countryData.population.toLocaleString("en-US");
  document.getElementById("currencies").innerHTML = countryData.currencies.filter(c => c.name).map(c => `${c.name} (${c.code})`).join(", ");
  document.getElementById("region").innerHTML = countryData.region;
}
      <div class="row">
        <div class="col-6"><img src="" alt=""></div>
        <div id="countries" class="col-6">
          <div><p>Capital:<span id="capital"></span></p></div>
          <div><p>dialing Code:<span id="dialing-code"></span></p></div>
          <div><p>Population:<span id="population"></span></p></div>
          <div><p>Currencies:<span id="currencies"></span></p></div>
          <div><p>Region:<span id="region"></span></p></div>
        </div>
      </div>

发布评论

评论列表(0)

  1. 暂无评论