c3nturi0n2013
c3nturi0n2013

Reputation: 21

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

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.

Upvotes: 2

Views: 51

Answers (2)

BEcho
BEcho

Reputation: 11

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;

Upvotes: 1

ZORGATI Achraf
ZORGATI Achraf

Reputation: 34

Try this code below:

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

Upvotes: 2

Related Questions