簡體   English   中英

從數組擴展現有對象的數據

[英]Extending data of an existing object from an array

我從 JSON 格式的 API 接收數組。 我想將它們合並到名為的嵌套數組中,該數組由對象graphData組成。 如何通過一個條目擴展數據對象?

mounted() {

   var i = 0;
   const axios = require('axios');
    //Usage
    axios.get("https://3.11.40.69:9001/app/usageUnitForCustomer/1521/2019-12-30/2020-12-30")
      .then(response => {
        const time = response.data.event_time; //["2019-12-30T14:06:21.000Z", "2019-12-30T14:06:21.000Z"]
        const unit = response.data.unit; //[44.67, 75.89]
        for (i = 0; i < 1; i++) {
          if (time[i] !== time[i + 1]) {
            this.graphData[1].data.time[i] = unit[i];
          }
        } 
      })
    //Revenue
    axios.get("https://3.11.40.69:9001/app/revenueUnitForMachine/345/2019-12-30/2020-12-30")
      .then(response => {
        const time = response.data.event_time; //["2019-12-30T14:06:21.000Z", "2019-12-30T14:06:21.000Z"]
        const unit = response.data.revenue; //[44, 75]
        for (i = 0; i < 10; i++) {
          if (time[i] !== time[i + 1]) {
            this.graphData[0].data.time[i] = unit[i];
          }
        } 

      })
  },
  data() {
      return {
        graphData: [
          {name: 'Revenue', data: {}},
          {name: 'Usage', data: {}}
        ]
      }
    }

執行上述代碼后,兩個數據對象仍然是空的。 結果如下所示,並顯示以下錯誤消息:

0:
name: "Revenue"
data: Object []

1:
name: "Usage"
data: Object []

Uncaught (in promise) TypeError: Cannot set property '0' of undefined

預期結果:

graphData: [
          {name: 'Revenue', data: {'2019-12-30T14:06:21.000Z': 448, '2019-12-30T14:06:22.000Z': 44}},
          {name: 'Usage', data: {'2019-12-30T14:06:21.000Z': 448, '2019-12-30T14:06:22.000Z': 44}}
        ]

有人有想法嗎?

您無法從 .then() 塊內訪問外部變量。 您應該能夠將整個外部塊變為async並使用await進行axios調用。

嘗試這樣的事情:

async mounted() {

   var i = 0;
   const axios = require('axios');
    //Usage

   const response = await axios.get("https://3.11.40.69:9001/app/usageUnitForCustomer/1521/2019-12-30/2020-12-30");

        const time = response.data.event_time;
        const unit = response.data.unit;
        for (i = 0; i < 1; i++) {
          if (time[i] !== time[i + 1]) {
            this.graphData[1].data.time[i] = unit[i];
          }
        } 


...

...繼續使用await來處理其余的axios調用。

我看到的一個問題是你在this.graphData[1].data.time[i] = unit[i];訪問time[i] this.graphData[1].data.time[i] = unit[i]; 但它沒有在您的對象中定義。

也許將它初始化為數組有幫助?

data() {
    return {
        graphData: [
          {name: 'Revenue', data: { time: [] }},
          {name: 'Usage', data: { time: [] }}
        ]
    }
}

編輯:好的,在您編輯預期結果后,我看到了另一個問題。

您可以嘗試設置這樣的值嗎?

this.graphData[1].data[time[i]] = unit[i];

注意time[i]周圍的額外[] time[i]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM