js let timeArr = ['2023-05-31 19', '2023-05-31 20', '2023-05-31 21']; let deviceIds = ['power_lift']; let resTempArr = [ { data: [{usageComment: '1层照明',},{usageComment: '2层照明',},{usageComment: '3层照明',}],key: 'power_lift',mdData: [[{power: 2.38,},{power: 2.48,},{power: 2.58,},{power: 2.68,},],[{power: 3.38,},{power: 3.48,},{power: 3.58,},{power: 3.68,},],[{power: 4.38,},{power: 4.48,},{power: 4.58,},{power: 4.68,}]]}, { data: [], key: 'power_all', mdData: [] }, { data: [], key: 'power_dianti', mdData: [] }, ];转换成 [ { time: '2023-05-31 19', '1层照明': 2.38, '2层照明': 3.38, '3层照明': 4.38, }, { time: '2023-05-31 20', '1层照明': 2.48, '2层照明': 3.48, '3层照明': 4.48, }, { time: '2023-05-31 21', '1层照明': 2.58, '2层照明': 3.58, '3层照明': 4.68, }, ]
时间: 2024-02-28 18:56:31 浏览: 90
使用js显示时间
可以使用以下代码将原始数据转换为目标格式:
```javascript
let resultArr = [];
for (let i = 0; i < timeArr.length; i++) {
let tempObj = {
time: timeArr[i]
};
for (let j = 0; j < resTempArr[0].data.length; j++) {
let usageComment = resTempArr[0].data[j].usageComment;
let mdData = resTempArr[0].mdData[j];
let power = mdData[i].power;
tempObj[usageComment] = power;
}
resultArr.push(tempObj);
}
```
这段代码会遍历时间数组 `timeArr`,对于每个时间点,再遍历 `resTempArr` 中第一个元素的 `data` 数组,将每个用电设备的用电量添加到临时对象 `tempObj` 中,最终将 `tempObj` 添加到结果数组 `resultArr` 中。
阅读全文