0

我看过很多类似的问题,但找不到。我的目的是获取硬币名称和价值。Coinmarketcap API 中有 2 个端点。注释行中的第一个给了我想要的输出并且它可以工作,但我需要第二个但不工作。两者都具有相似的 JSON 结构。

像这样的第一个端点的输出和 JSON https://pastebin.com/xSS85Sbd

name: 'Bitcoin', price: 43973.31953486187,
name: 'Ethereum', price: 3097.8947589293316

我在 2 日遇到的一些错误和 JSON https://pastebin.com/0sDXXwxm

coin.data.map is not a function
Cannot read properties of undefined (reading 'name')

我在下面尝试了更多和几个带有和不带地图的 console.log 品种,但都没有成功。

coin.map(a => ({ name: a.name, price: a.quote.USD.price}))
coin.data.map(a => ({ name: a.name, price: a.quote.USD.price}))
async function getCoin(){
  try {
    //const response = await axios.get('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?limit=2', {
    const response = await axios.get('https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest?symbol=BTC,ETH', {
      headers: {
        'X-CMC_PRO_API_KEY': 'key',
      },
    });

    const coin = response.data;
    const result = coin.data.map(a => ({ name: a.name } ))

    console.log(result);

    //return coin;

    } catch(ex) {
    console.log(ex);
    throw ex;
  }
}
getCoin()

我真的想知道我错在哪里。非常感谢。

4

1 回答 1

0

它无法运行,因为它们具有不同的结构。

在第一个 JSONdata数组,所以你可以使用 map

{
...
"data":[{"id":1,"...
...
}

第二个data对象,所以它会抛出错误coin.data.map is not a function

{
...
"data":{"BTC"...
...
}

更新

你可以像这样获得硬币信息

const result = Object.keys(coin.data).map(coinName => {
  const coinInfo = coin.data[coinName][0]
  return {
    name: coinInfo.name,
    price: coinInfo.quote.USD.price
  }
})
console.log('result: ', result)
于 2022-02-16T10:18:25.317 回答