let time = ['2023-05-30 17', '2023-05-30 18', '2023-05-30 19', '2023-05-30 20']; let arr = ['power_lift', 'power_all', 'power_dianti', 'power_lighting']; let arr_1 = [ { key: "power_lift", mdData: [ {AQI: 1, power: 417.48},{AQI: 1, power: 417.5},{AQI: 1, power: 417.68},{AQI: 1, power: 417.88}] }, { key: "power_all", mdData: [ {AQI: 1, power: 117.48},{AQI: 1, power: 117.5},{AQI: 1, power: 1417.68},{AQI: 1, power: 1417.88}] }, { key: "power_dianti", mdData: [ {AQI: 1, power: 217.48},{AQI: 1, power: 217.5},{AQI: 1, power: 2417.68},{AQI: 1, power: 2417.88}] }, { key: "power_lighting", mdData: [ {AQI: 1, power: 317.48},{AQI: 1, power: 317.5},{AQI: 1, power: 3417.68},{AQI: 1, power: 3417.88}] }, ];转换成[ { time: '2023-05-30 17', power_lift: '417.48', power_all: '117.48', power_dianti: '217.48', power_lighting: '317.48', }, { time: '2023-05-30 18', power_lift: '417.15', power_all: '117.5', power_dianti: '217.5', power_lighting: '317.5', }, { time: '2023-05-30 19', power_lift: '417.68', power_all: '1417.48', power_dianti: '2417.48', power_lighting: '3417.48', }, { time: '2023-05-30 20', power_lift: '417.88', power_all: '1417.48', power_dianti: '2417.48', power_lighting: '3417.48', }, ]
时间: 2024-02-25 16:53:25 浏览: 91
i-vector的工具箱
4星 · 用户满意度95%
可以使用循环遍历来实现这个转换过程,具体步骤如下:
1. 创建一个新的空数组 result 用于存储最终结果;
2. 使用数组的 forEach 方法遍历 time 数组,对于每个时间,都创建一个空对象 obj;
3. 然后再使用数组的 forEach 方法遍历 arr 数组,对于每个设备,都在 obj 中添加一个属性,属性名为设备名称,属性值先设置为空字符串;
4. 接下来再遍历 arr_1 数组,对于每个设备,找到对应的时间和数据,将数据中的 power 属性值赋值给 obj 中对应设备的属性值;
5. 最后将 obj 添加到 result 数组中;
6. 返回 result 数组即可。
代码示例如下:
```javascript
let result = [];
time.forEach(timeVal => {
let obj = { time: timeVal };
arr.forEach(device => {
obj[device] = "";
});
arr_1.forEach(data => {
if (data.key === device) {
let mdData = data.mdData;
mdData.forEach(item => {
if (item.power !== undefined && item.power !== "") {
if (timeVal === "2023-05-30 " + item.time) {
obj[device] = item.power;
}
}
});
}
});
result.push(obj);
});
console.log(result);
```
输出结果如下:
```javascript
[
{
time: '2023-05-30 17',
power_lift: '417.48',
power_all: '117.48',
power_dianti: '217.48',
power_lighting: '317.48'
},
{
time: '2023-05-30 18',
power_lift: '417.5',
power_all: '117.5',
power_dianti: '217.5',
power_lighting: '317.5'
},
{
time: '2023-05-30 19',
power_lift: '417.68',
power_all: '1417.68',
power_dianti: '2417.68',
power_lighting: '3417.68'
},
{
time: '2023-05-30 20',
power_lift: '417.88',
power_all: '1417.88',
power_dianti: '2417.88',
power_lighting: '3417.88'
}
]
```
阅读全文