Matt
Matt

Reputation: 78

How do I access nested information in a JSON API response?

I am trying to build a simple CLI cryptocurrency tracker app. The application performs a successful API call and returns the following response:

[ { exchange: 'binance',
    base: 'ADA',
    quote: 'BTC',
    price_quote: '0.00001663',
    timestamp: '2019-04-08T16:36:00Z' },
  { exchange: 'binance',
    base: 'ADX',
    quote: 'BTC',
    price_quote: '0.00003316',
    timestamp: '2019-04-08T16:35:00Z' },
...]

How do I access a specific object within the response? For example, how could I return the entire object where base: 'ADA?

Here is the simple Axios call that returns the JSON response:

axios.get("https://api.nomics.com/v1/exchange-markets/prices?key=" + apiKey + "&currency=BTC&exchange=binance")
    .then(function (response) {
      console.log(response.data)
    })

Upvotes: 0

Views: 472

Answers (2)

richard nelson
richard nelson

Reputation: 265

axios.get("https://api.nomics.com/v1/exchange-markets/prices?key=" + apiKey + "&currency=BTC&exchange=binance")
.then(function (response) {
  console.log(response.data.find(data=>data.base==='ADA'))
}

The “find” function will go through every item of the array until it finds the item matches the provided boolean condition and returns it.

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

You can use find

let response = [ { exchange: 'binance',base: 'ADA',quote: 'BTC',price_quote: '0.00001663',timestamp: '2019-04-08T16:36:00Z' },
{exchange: 'binance', base: 'ADX',quote: 'BTC',price_quote: '0.00003316',timestamp: '2019-04-08T16:35:00Z' },]

let value = response.find(e => e.base === 'ADA')

console.log(value)

Upvotes: 1

Related Questions