How to get data from nested data in Rest Countries API v3

526 views Asked by At

I am trying to get data from Rest API Countries v3. Data is structured as follows:

In the main object, let's call it CountryObject, there is the currencies property, which contains data I want to display.

export interface CountryObject {
   currencies?:  Currencies;
}

Currencies Object includes different keys inside it of two types: Aed and BAM to be exact. The interface looks like this:

export interface Currencies {
   EUR?: Aed;
   SEK?: Aed;
   XPF?: Aed;
   XOF?: Aed;
   BAM?: BAM;
   JOD?: Aed;
   USD?: Aed;
}

The final interfaces are BAM and Aed.

export interface Aed {
   name:   string;
   symbol: string;
}

export interface BAM {
   name: string;
}

a sample response is: "currencies": { "JPY": { "name": "Japanese yen", "symbol": "¥" }

My question is, how do I get the name property of BAM or Aed types based on the value returned by the API?

1

There are 1 answers

0
Todd On BEST ANSWER

Overall I think you just need to indicate that your interface supports the 'index signature' - which allows you to access a variable key.

interface Aed {
   name:   string;
   symbol: string;
}

interface BAM {
   name: string;
}

interface Currencies {
   EUR?: Aed;
   SEK?: Aed;
   XPF?: Aed;
   XOF?: Aed;
   BAM?: BAM;
   JOD?: Aed;
   USD?: Aed;
   JPY?: Aed;
   [key: string]: Aed | BAM | undefined;
}

interface CountryObject {
   currencies?: Currencies;
}

const countyObject: CountryObject = { currencies: { JPY: { name: "Japanese yen", symbol: "¥" }}}

// looping over results
Object.entries(countyObject.currencies ?? {}).forEach(([key, value]) => {
  if (value) {
    if ('symbol' in value) {
      console.log(`${key} is an Aed ${value.name} ${value.symbol}`)
    } else {
      console.log(`${key} is an BAM ${value.name}`)
    }
  }
})

// direct access by various keys
const currentCurrency: string = 'JPY'
const currency = countyObject.currencies?.[currentCurrency]

if (currency) {
  if ('symbol' in currency) {
    console.log(`${currentCurrency} is an Aed ${currency.name} ${currency.symbol}`)
  } else {
    console.log(`${currentCurrency} is an BAM ${currency.name}`)
  }
}