我看过很多类似的问题,但都找不到。我的目的是得到硬币的名字和价值。Coinmarketcap中有两个端点。在注释行中的第一个给出了我想要的输出,它可以工作,但是我需要第二个输出,但不能工作。两者都有相似的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()我真想知道我哪里错了。非常感谢。
发布于 2022-02-16 10:18:25
它不能运行,因为它们有不同的结构。
在第一个JSON中,data是数组,所以您可以使用映射
{
...
"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)https://stackoverflow.com/questions/71134362
复制相似问题