node.js从数组或对象中获取数据

时间:2019-01-01 20:02:22

标签: javascript node.js json

我尝试仅检索主体对象上的数据,本节对此我感到困惑

我的代码

      coin_price: async function(callback){
        var coingecko = await CoinGeckoClient.simple.price({
                ids: config.tickercoins,
                vs_currencies: ['usd', 'btc', 'idr', 'eur', 'jpy', 'krw'],
              });
            callback(null, coingecko);
      },

结果:

"coin_price": {
"success": true,
"message": "OK",
"code": 200,
"data": {
  "loki-network": {
    "usd": 0.202249,
    "btc": 0.000055,
    "idr": 2905.52,
    "eur": 0.176356,
    "jpy": 22.18,
    "krw": 225.42
     }}},

我想成为这样:

    "coin_price": {
    "usd": 0.202249,
    "btc": 0.000055,
    "idr": 2905.52,
    "eur": 0.176356,
    "jpy": 22.18,
    "krw": 225.42
    },

然后我尝试编辑我的代码,例如:

      coin_price: async function(callback){
        var coingecko = await CoinGeckoClient.simple.price({
                ids: config.tickercoins,
                vs_currencies: ['usd', 'btc', 'idr', 'eur', 'jpy', 'krw'],
              });
            callback(null, coingecko.data);
      },

结果:

     "coin_price": {
       "loki-network": {
       "usd": 0.202249,
       "btc": 0.000055,
       "idr": 2905.52,
       "eur": 0.176356,
       "jpy": 22.18,
       "krw": 225.42
       }},

代码callback(null, coingecko.data[0]);不起作用

有没有例子,结果可以如我所愿?

2 个答案:

答案 0 :(得分:1)

//this is the resposne data let json = {"coin_price": { "success": true, "message": "OK", "code": 200, "data": { "loki-network": { "usd": 0.202249, "btc": 0.000055, "idr": 2905.52, "eur": 0.176356, "jpy": 22.18, "krw": 225.42 }}}} let coin_price = json.coin_price.data["loki-network"] //this is where you access the data console.log(coin_price) 对象使用键coingecko.data,而不是"loki-network"。调整回调,使其返回该属性:

0

答案 1 :(得分:0)

就像@Mark Meyer在评论中说的那样,为了获得想要的json,可以执行以下操作:

.hero div:first-child {
  color: red;
}
.hero div:last-child{
  color: red;
}