s-e1
s-e1

Reputation: 85

Accessing an API nested object

I'm trying to access from an API the values of some currencies, and I'm not managing to get them from within the function.

The API returns after parsing this: {"ETH":{"USD":188.01},"BTC":{"USD":10330.41}}

This is the code I used:

fetch('https://min-api.cryptocompare.com/data/pricemulti?fsyms=ETH,BTC&tsyms=USD')
    .then(val => val.json()).then(data => {
        info = data; for (var item in data) { console.log(item.USD) }
    });

It logs undefined.

When I do in it console.log(item), it logs ETH and BTC as strings and not as objects as they should be. When I write in the console (outside of .then) info.ETH.USD, I get the results.

What did I get wrong?

Upvotes: 1

Views: 80

Answers (2)

Vijay Rajpurohit
Vijay Rajpurohit

Reputation: 1352

I think you are confused with JSON object manipulations. While playing around with JSON Objects, Learn a few things which generally helps.

Fetching value from JSON Object:

var obj = {"ETH":{"USD":188.01},"BTC":{"USD":10330.41}};

For fetching at the initial level:

 obj["ETH"] // return {"USD":188.01}

Fetching at nested level:

 obj["ETH"]["USD"] // return 188.01

In your case, you are printing keys only

Update your syntax:

for(let item in data) {
    console.log(data[item]) 
 }

Output:

{
  "USD": 187.98
}
{
  "USD": 10302.56
}

Upvotes: 1

Rohit Kashyap
Rohit Kashyap

Reputation: 1592

The reason it was not working for you because you were looping through the object and returning the keys and not the actual object. item refers to keys of the object.

Try this:

fetch('https://min-api.cryptocompare.com/data/pricemulti?fsyms=ETH,BTC&tsyms=USD').
then(res => res.json())
.then(data => {
  console.log("The object", data)
  for(var item in data) {
    console.log(data[item])
  }
})

Now you can refer to the USD property as data[item].USD.

Upvotes: 2

Related Questions