从第三方API获取如何格式的数据:
[{
"device": "二(1)班",
"name": "二(1)班-电量",
"value": 10
},
{
"device": "二(1)班",
"name": "二(1)班-电流",
"value": 11
},
{
"device": "二(1)班",
"name": "二(1)班-电功率",
"value": 12
},
{
"device": "二(2)班",
"name": "二(2)班-电量",
"value": 13
},
{
"device": "二(2)班",
"name": "二(2)班-电流",
"value": 14
},
{
"device": "二(2)班",
"name": "二(2)班-电功率",
"value": 15
}
]
如何按照device相同数值的班级合并成一个数组格式如:
{"device": "二(1)班","name": "二(1)班-电量,二(1)班-电流,二(1)班-电功率","value": "10,11,12"},
{"device": "二(2)班","name": "二(2)班-电量,二(2)班-电流,二(2)班-电功率","value": "13,14,15"}]
在JavaScript中,你可以使用reduce
函数来将具有相同"device"的对象合并成一个新的数组。下面是一个例子:
let data = [
{ "device": "二(1)班", "name": "二(1)班-电量", "value": 10 },
{ "device": "二(1)班", "name": "二(1)班-电流", "value": 11 },
{ "device": "二(1)班", "name": "二(1)班-电功率", "value": 12 },
{ "device": "二(2)班", "name": "二(2)班-电量", "value": 13 },
{ "device": "二(1)班", "name": "二(2)班-电流", "value": 14 },
{ "device": "二(1)班", "name": "二(2)班-电功率", "value": 15 }
];
let result = data.reduce((acc, curr) => {
let found = acc.find(item => item.device === curr.device);
if (found) {
found.name += ',' + curr.name;
found.value += ',' + curr.value;
} else {
acc.push({
device: curr.device,
name: curr.name,
value: curr.value
});
}
return acc;
}, []);
console.log(result);
在这个脚本中,我们遍历数据数组,并使用reduce
函数来创建一个新的结果数组。对于每一个元素,它会检查是否已经在结果数组中找到一个相同的"device"。如果找到,它会将当前元素的"name"和"value"添加到找到的元素的"name"和"value"上。如果没有找到,它会将当前元素添加到结果数组中。最后,它将打印出结果数组。
@漏刻有时