javascript二维数组按指定要求进行对象合并遍历的算法开发
项目原数据
从第三方API获取如何格式的数据:
- "device": "二(1)班",不同班级名称,会重复
- "name": "二(1)班-电量",不同班级的数据标准
- "value": 10,数据值
那实际开发中,如何根据需要进行数据的合并和计算呢?
javascript
[{
"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相同数值的班级合并成一个数组格式如:
php
{"device": "二(1)班","name": "二(1)班-电量,二(1)班-电流,二(1)班-电功率","value": "10,11,12"},
{"device": "二(2)班","name": "二(2)班-电量,二(2)班-电流,二(2)班-电功率","value": "13,14,15"}]
算法开发
在JavaScript中,你可以使用reduce
函数来将具有相同"device"的对象合并成一个新的数组。下面是一个例子:
javascript
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"上。如果没有找到,它会将当前元素添加到结果数组中。最后,它将打印出结果数组。
@漏刻有时