How can I write code using this key in javascript to extract the value?

Viewed 43

This is the data I fetch through an API:

{ "0x5af2be193a6abca9c8817001f45744777db30756": { "usd": 0.11039 }}

but when I try to access the data to put in html using:

var price = data.0x5af2be193a6abca9c8817001f45744777db30756.usd;

The error reads back:

Uncaught SyntaxError: Invalid or unexpected token

I think it is bc it doesn't identify 0x5af2be193a6abca9c8817001f45744777db30756
as a string but I don't know how to fix it.

2 Answers

Try this code below:

var price = data["0x5af2be193a6abca9c8817001f45744777db30756"].usd;

According to the JavaScript MDN Documentation for Objects and Properties

"An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation."

Your key '0x5af2be193a6abca9c8817001f45744777db30756' is an invalid identifier because it starts with a number. You can access it using square bracket notation:

var price = data["0x5af2be193a6abca9c8817001f45744777db30756"].usd;
Related