商品数据图表 - 在 JSON 中获取日期和值的问题

Charting Commodity Data - Issue getting the dates and values in JSON

 {
  "data": {
    "success": true,
    "timeseries": true,
    "start_date": "2022-02-01",
    "end_date": "2022-03-02",
    "base": "RUB",
    "rates": {
      "2022-02-01": {
        "USD": 0.012922641020611143
      },
      "2022-02-02": {
        "USD": 0.013024953827785636
      },
      "2022-02-03": {
        "USD": 0.013111232627449121
      },
      "2022-02-04": {
        "USD": 0.013080360583812869
      }
    }
  }
}

以上是我的 axios 查询返回的 JSON。我尝试使用循环和 forEach 来捕获图表的 x、y 的日期和美元值,但我似乎无法同时获取它们。下面是我目前的图表代码。

function fnChart04() {
    var chartArray = [];
    var yesterday = moment().subtract(24, 'hours').format('YYYY-MM-DD');
    var url = "https://commodities-api.com/api/timeseries?access_key=XYZed&start_date=2022-02-01&end_date="+yesterday+"&base=RUB&symbols=USD";
    var header = { headers: {'Accept': 'application/json; odata=nometadata'} };
    axios.get(url, header).then(function (response) {
        var results = response.data;

        let rate = results.data.rates.USD;
        let date = results.data.rates[0];

        //issue is here - I cannot figure out how to loop through rates to separate the date and the USD value to add to the chartArray.

        chartArray.push({x: date, y: rate});

        new Chart(document.getElementById("myChart04"), {
            type: 'line',
            data: {
                labels: chartArray.map(function(a) { return a.x; }),
                datasets: [{ 
                    data: chartArray,
                    label: "RUB | USD",
                    borderColor: "#f93154",
                    backgroundColor: "#fee3e8",
                    fill: true
                }]
            },
            options: {
                response: true,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
                
            });
    });
        
}

任何有关如何执行此操作的建议都将不胜感激。我知道我错过了一些简单的东西。

您可以使用 Object.keys 遍历 rates 的键,然后推送到 chartArray

let results = {
  "data": {
    "success": true,
    "timeseries": true,
    "start_date": "2022-02-01",
    "end_date": "2022-03-02",
    "base": "RUB",
    "rates": {
      "2022-02-01": {
        "USD": 0.012922641020611143
      },
      "2022-02-02": {
        "USD": 0.013024953827785636
      },
      "2022-02-03": {
        "USD": 0.013111232627449121
      },
      "2022-02-04": {
        "USD": 0.013080360583812869
      }
    }
  }
}

let chartArray = [];
Object.keys(results.data.rates).forEach((key) => chartArray.push({x: key,y: results.data.rates[key]["USD"]}))

console.log(chartArray)