后台返回的数据源是没有进行分组的
let arr=[{
time: '2.28',
station: '武昌站',
kind: '火车',
count: 30
},
{
time: '2.28',
station: '汉口站',
kind: '飞机',
count: 10
},
{
time: '2.28',
station: '武汉站',
kind: '火车',
count: 20
},
{
time: '2.28',
station: '武汉站',
kind: '火车',
count: 40
},
{
time: '2.28',
station: '武汉站',
kind: '飞机',
count: 20
},
{
time: '2.29',
station: '汉口站',
kind: '火车',
count: 10
},
{
time: '2.29',
station: '汉口站',
kind: '飞机',
count: 30
},
{
time: '2.29',
station: '武昌站',
kind: '飞机',
count: 60
},
{
time: '2.29',
station: '武昌站',
kind: '火车',
count: 10
},
{
time: '2.29',
station: '武昌站',
kind: '火车',
count: 30
}
];
前端需求展示所需要的数据格式1
先根据时间筛选车站,然后根据车站计算当前的乘车方式还有多少票
[{
time: '2.28',
data:[{
station:'武昌站',
children:[{
kind:'火车',
count:30
},{
kind:'飞机',
count:60
}]
},{
station:'武汉站',
children:[{
kind:'火车',
count:30
},{
kind:'飞机',
count:60
}]
}]
},
{
time: '2.29',
data:[]
}
];
具体代码如下
let newArr = arr.reduce((prev, item) => {
//先根据时间进行分组,没有当前时间则添加到数组中
let rst = prev.find(row => row.time == item.time);
let obj = {
station: item.station,
children: [{
kind: item.kind,
count: item.count
}]
};
if (!rst) {
prev.push({
time: item.time,
data: [obj]
});
} else {
// 已经存在了当前时间
let station = rst.data.find(row => row.station == item.station);
// 根据车站分组
if (!station) {
rst.data.push(obj);
} else {
// 根据票种进行分组
let kind = station.children.find(row => row.kind == item.kind);
if (!kind) {
station.children.push({
kind: item.kind,
count: item.count
});
} else {
kind.count += item.count;
}
}
}
return prev;
}, []);
console.log(newArr)
前端需求展示所需要的数据结构2
具体代码如下
let newArr = arr.reduce((prev, item) => {
let time = prev.find(row => row.time == item.time);
if (!time) {
prev.push(item)
} else {
let station = prev.find(row => row.time == item.time && row.station == item.station);
if (!station) {
prev.push(item)
} else {
let kind = prev.find(row => row.time == item.time && row.station == item.station && row.kind == item.kind);
if (!kind) {
prev.push(item)
} else {
kind.count += item.count;
}
}
}
return prev;
}, [])
console.log(newArr)