开发者问题收集

从数组扩展现有对象的数据

2020-01-12
82

我从 API 接收 JSON 格式的数组。我想将它们合并到名为 graphData 的嵌套数组中,该数组由对象 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}}
        ]

有人有想法吗?

2个回答

我发现的一个问题是,您在 this.graphData[1].data.time[i] = unit[i]; 中访问 time[i] ,但它未在您的对象内部定义。

也许将其初始化为数组有帮助?

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

编辑: 好的,在您编辑预期结果后,我发现了另一个问题。

您可以尝试像这样设置值吗?

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

请注意 time[i] 周围的额外 []

jumper85
2020-01-12

您无法从 .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];
          }
        } 


...

... 继续对其余 axios 调用使用 await

ram
2020-01-12