简体   繁体   中英

JavaScript, API, filtering array

I want to start function which create me table, iam using if and indexOf in .foreach, and i wish that shows me the table ony if the value of input will be exactly the same as a first item of array in tah case name:germany. What iam doing wrong? https://scr.hu/eyjnr0

function showCountriesList(resp) {

 var url = 'https://restcountries.eu/rest/v2/name/';
 var createdTable = createNewTable();
 var countryName = $('#country-name').val();

 resp.forEach(function(item) {
  var row = document.createElement('tr');
  row.innerHTML = `
   <td><img style="width: 60px; height: 60px; object-fit: cover" src=${item.flag}></img></td>
   <td>${item.name}</td>
   <td>${item.capital}</td>
   <td>${item.alpha2Code}</td>
   <td>${item.timezones}</td>
  `;
   if (countryName === url.indexOf([item.name])) {
    createdTable.appendChild(row); }
 });

}

The information you provided is not clear enough to give a conclusive answer.

Your if statement is invalid and will always be false. Assuming that the countryName variable holds a string and the indexOf function returns a number. Also your usage if the indexOf function is wrong as it expects a string not an array.

if (countryName === url.indexOf([item.name])) {
createdTable.appendChild(row); }

I am assuming that the above code is trying to check whether the countryName value is the same as the one in the url.

I suggest you try using the string function includes

if( url.includes(countryName)) createdTable.appendChild(row);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM