简体   繁体   中英

How to access properties from a Javascript object?

I have an api call that produces the follow results in the console (after pairing it down using map() ).

{…}
​
CHANGE24HOUR: "$ 11.16"
​
CHANGEDAY: "$ 3.31"
​
CHANGEPCT24HOUR: "6.73"
​
CHANGEPCTDAY: "1.90"
​
FROMSYMBOL: "Ξ"
​
HIGH24HOUR: "$ 183.38"
​
HIGHDAY: "$ 183.38"

However, no matter what I try I can't get at it's properties. The object is called 'coinStats'.

I have tried the following:

coinStats.HIGHDAY = undefined
coinStats['HIGHDAY'] = undefined
coinStats["HIGHDAY"] = undefined

Tried to convert it to an array to see if that would help using

Object.values(coinStats)  // Would not work

I am sure the answer is so simplistic. But I am just not sure what it is?

The original raw api results are in the following shape:

(1) […]
​
0: Object { CoinInfo: {…}, RAW: {…}, DISPLAY: {…} }
​
length: 1
​
<prototype>: [

The info I am looking for is in DISPLAY -> USD. I used a map() function to return that sub-object.

The code I am using to fetch the data is essentially the following:

const API = 'https://min-api.cryptocompare.com/data/top/mktcapfull?tsym=USD&page=1';

fetch(API)
  .then(results => results.json())
  .then(coinData => {

    const view = coinData.Data.filter(obj => { return obj.CoinInfo.Name === TRX});

  })

const coinFeedAbridged = view.map(item => item.DISPLAY.USD);

const coinStats = coinFeedAbridged[0];

console.dir(coinStats);

I can't access coinStats.HIGHDAY for example... I get 'undefined'.

The fetch call is async, so you can't access the view variable until the call is finished. The code calls the async function and runs the next line, so view variable will be undefined. You have to handle the data inside the fetch callback function, where the data is known.

const API = 'https://min-api.cryptocompare.com/data/top/mktcapfull?tsym=USD&page=1';

  fetch(API)
    .then(results => results.json())
    .then(coinData => {

      const view = coinData.Data.filter(obj => { 
        return obj.CoinInfo.Name === 'TRX'
       });

      const coinFeedAbridged = view.map(item => item.DISPLAY.USD);

      const coinStats = coinFeedAbridged[0];
      console.log(coinStats);

    })
  }

You can test it out in this fiddle. https://jsfiddle.net/gran7ptk/1/

Change line - Add inverted commas to Text "TRX".

 const view = coinData.Data.filter(obj => { return obj.CoinInfo.Name
 === TRX});

to const view = coinData.Data.filter(obj => { return obj.CoinInfo.Name === "TRX"});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM