您的位置:首页 > Web前端 > JavaScript

将一个js数组按日期分组的实现方法

2018-02-07 14:49 671 查看
举例说明:

产品需求:



假如后台返回格式:
var data = [
{"time": 1517482336545, "location": "浦东"},
{"time": 1517482336543, "location": "静安"},
{"time": 1516344919173, "location": "内环"},
{"time": 1515574927334, "location": "五环"},
{"time": 1517482336544, "location": "苏州"}
];
这就需要前台再处理成我们需要的数据了。
步骤:将毫秒转换成日期格式----处理数组---返回需要的数据格式[{time:"",location:[]}]
方法:
//转换时间
function transDate(n) {
var date = new Date(n);
var Y = date.getFullYear() + '-';
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
return (Y + M + D)
}
//处理原数组
for(var i=0;i<arr.length;i++){
var timeitem = transDate(arr[i].time);
console.log(arr[i].time);
arr[i].time = timeitem;
}
//返回所需数据格式
const mapLoction = function(arr) {
let newArr = [];
arr.forEach((address, i) => {
let index = -1;
let alreadyExists = newArr.some((newAddress, j) => {
if (address.time === newAddress.time) {
index = j;
return true;
}
});
if (!alreadyExists) {
newArr.push({
time: address.time,
location: [address.location]
});
} else {
newArr[index].location.push(address.location);
}
});
return newArr;
};
console.log(mapLoction(data));
之后就是渲染数据了


打印结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js 数组分组