How to get a list from a JSON

Asked

Viewed 87 times

5

I am trying to make a list of currencies from a JSON text, for this I am using the API "exchangeratesapi.io".

Using Javascript I achieved some success:

const url = 'https://api.exchangeratesapi.io/latest?base=USD'

fetch(url)
  .then(result => result.json())
  .then(json => console.log(json.rates))

But I would like to create a list with only the abbreviated names of the coins, for example:

{
  BGN,
  NZD,
  ILS,
  RUB,
  CAD,
  USD,
  PHP,
  CHF,
  AUD,
  JPY,
  TRY,
  HKD,
  MYR,
  HRK,
  CZK,
  IDR,
  DKK,
  NOK,
  HUF,
  GBP,
  MXN,
  THB,
  ISK,
  ZAR,
  BRL,
  SGD,
  PLN,
  INR,
  KRW,
  RON,
  CNY,
  SEK,
  EUR 
}

Or even create an array containing all of them from there, for example:

let currency = ["BGN", "NZD", "ILS", "RUB", "CAD", "USD", "PHP", "CHF", "AUD", "JPY", "TRY", "HKD", "MYR", "HRK", "CZK", "IDR", "DKK", "NOK", "HUF", "GBP", "MXN", "THB", "ISK", "ZAR", "BRL", "SGD", "PLN", "INR", "KRW", "RON", "CNY", "SEK", "EUR"];

What technologies or methods should I use to achieve this?

1 answer

6


In this case just create an array using let currencies = Object.keys(json.rates);.
The Object.keys will extract all keys from an object and create an array with them.

That is to say:

const url = 'https://api.exchangeratesapi.io/latest?base=USD'

fetch(url)
  .then(result => result.json())
  .then(json => {
    const currencies = Object.keys(json.rates);
    console.log(currencies);
  })

Browser other questions tagged

You are not signed in. Login or sign up in order to post.