const list = [
{
"station": "张三",
"num": "0",
"timeTemp": "2024-03-05 00:00"
},
{
"station": "李四",
"num": "0",
"timeTemp": "2024-03-05 00:00"
},
{
"station": "张三",
"num": "0",
"timeTemp": "2024-03-05 01:00"
},
{
"station": "李四",
"num": "0",
"timeTemp": "2024-03-05 01:00"
},
{
"station": "李四",
"num": "0",
"timeTemp": "2024-03-05 01:00"
},
{
"station": "王五",
"num": "0",
"timeTemp": "2024-03-05 01:00"
},
{
"station": "王五",
"num": "0",
"timeTemp": "2024-03-05 01:00"
},
{
"station": "张三",
"num": "0",
"timeTemp": "2024-03-05 02:00"
},
{
"station": "王五",
"num": "0",
"timeTemp": "2024-03-05 02:00"
},
{
"station": "张三",
"num": "0",
"timeTemp": "2024-03-05 02:00"
},
{
"station": "张三",
"num": "0",
"timeTemp": "2024-03-05 02:00"
},
];
const result = list.reduce((accumulator, currentItem) => {
// 查找累积器中是否已经有一个与当前项具有相同station的对象
const found = accumulator.find(item => item.station === currentItem.station);
if (found) {
// 如果找到了,将当前项的num添加到找到的对象的num数组中
if (!Array.isArray(found.num)) {
found.num = [found.num]; // 如果num还不是数组,则先将其转换为数组
}
found.num.push(currentItem.num); // 添加num到数组中
} else {
// 如果没有找到,则创建一个新对象并将其添加到累积器中
accumulator.push({ ...currentItem, num: [currentItem.num] });
}
return accumulator;
}, []); // 初始值是一个空数组