TransWikia.com

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

Stack Overflow Asked by c3nturi0n2013 on January 9, 2021

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;

Correct answer by ZORGATI Achraf on January 9, 2021

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;

Answered by BEcho on January 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP