Alex Denor
Alex Denor

Reputation: 137

How to get an element of an object?

I want to reach an element of an object from an API endpoint (https://restcountries.eu/rest/v2/all), more precisely the "name" from "currencies" but it always return undefined.

I have tried currencies.name and currencies["name"] but none of these works.

const countries = document.getElementById('countries');

var request = new XMLHttpRequest();

request.open('GET', 'https://restcountries.eu/rest/v2/all', true);

data.forEach(name => {
        const h1 = document.createElement('h1');
        h1.textContent = name.capital; //this one works just fine

        const h2 = document.createElement('h2');
        h2.textContent = name.currencies.name; //the problem is in here

        countries.appendChild(h1);
        countries.appendChild(h2);
 });

I want to get for example "Afghan afghani", not undefined like before.

Upvotes: 1

Views: 139

Answers (3)

Ricardo Montuan
Ricardo Montuan

Reputation: 78

You can do the following and you don't have to worry if a country has more than one currency:

const countries = document.getElementById('countries');
const request = new XMLHttpRequest();

request.open('GET', 'https://restcountries.eu/rest/v2/all', true);

request.onload = function (e) {
  if (request.readyState === 4) {
    if (request.status === 200) {

      const data = JSON.parse(request.responseText);

      data.forEach(function(item){

        //add country
        const h1 = document.createElement('h1');
        h1.textContent = item.name; 
        countries.appendChild(h1);

        //add currencies
        item.currencies.forEach(function(currency){
          const h2 = document.createElement('h2');
          h2.textContent = currency.name; 
          countries.appendChild(h2);
        });

      });  

    } else {
      console.error(request.statusText);
    }
  }
};

request.onerror = function (e) {
  console.error(request.statusText);
};

request.send(null);

Upvotes: 0

Antonio Gamiz Delgado
Antonio Gamiz Delgado

Reputation: 2113

THE problem is that currencies is an array.

So you should use currencies[0].name, for instance, to get the name of the first currency.

Upvotes: 1

TeaNyan
TeaNyan

Reputation: 5079

Your problem lies in currencies being an array.

Your JSON

You have to say name.currencies[0].name or if you have multiple currencies, you will have to iterate through the array to get all of them.

Upvotes: 3

Related Questions