简体   繁体   中英

TypeError: Cannot read properties of undefined (reading 'name') in js

  const html = `
        <article class="country ${className}">
          <img class="country__img" src="${data.flags.png}" />
          <div class="country__data">
            <h3 class="country__name">${data.name.common}</h3>
            <h4 class="country__region">${data.region}</h4>
            <p class="country__row"><span>👫</span>${(
              +data.population / 1000000
            ).toFixed(1)}</p>
            <p class="country__row"><span>🗣️</span>${data.languages[0]}</p>
            <p class="country__row"><span>💰</span>${
              data.currencies[0].name
            }</p>

          </div>
        </article>
  `;
  console.log(data);
  countriesContainer.insertAdjacentHTML('beforeend', html);
  //   countriesContainer.style.opacity = 1;
};

This is the code to output the data

  //country 1
  fetch(`https://restcountries.com/v3.1/name/${country}`)
    .then(response => {
      console.log(response);
      return response.json();
    })
    .then(data => {
      renderCountry(data[0]);
      const neighbour = data[0].borders[0];

      //if theres no neighbour return immedaitely
      //thats what the ! is for
      if (!neighbour) return;

      //country 2
      return fetch(`https://restcountries.com/v3.1/alpha/${neighbour}`);
    })
    .then(response => response.json())
    .then(data => renderCountry(data[0], 'neighbour'))

this is the code to get the data through promises

currencies: NGN: {name: 'Nigerian naira', symbol: '₦'} And this is the array sample array, im trying to get the 'name' i think data.currencies[0].name should work and its not

if i run the code this way,

<p class="country__row">< <span>💰>/span>${data.currencies[0]}</p>

i get undefined without the real data showing which is the real problem

if i run it this way,

<p class="country__row"><span>< 💰</span>${data.currencies[0].name}</p>

i get this error <TypeError: Cannot read properties of undefined (reading 'name') and i > dont know why

<the main problem here is when i dont add.name when trying to read and output the data and just run data.currencies[0], it gives me undefined and when i try to run data.currencies[0].name it gives me typeerror and i dont think it should be because i think im reading the data correctly.

In the data returned, currencies is NOT an array... But an object. So you can not use currencies[0] . You need to know the property name.

Now... You can "know" it using Object.keys which create an array with the keys found in an object.
And then use the first array item as a key for the object.

So Object.keys(data.currencies)[0] would give you the first key in the currencies object.

 const countries = ["nigeria", "brazil", "canada", "france", "italy"] countries.forEach((country) => fetch(`https://restcountries.com/v3.1/name/${country}`).then(response => { return response.json(); }).then(data => { const coutryData = data[0] const countryCurrencies = coutryData.currencies console.log(`${country}: ${countryCurrencies[Object.keys(countryCurrencies)[0]].name}`) }) )
 .as-console-wrapper { max-height: 100%;important: top; 0; }

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