查询出来类似这样的数据(大概意思):
[{
"id": 1,
"flightDate": "2016-05-11"
}, {
"id": 2,
"flightDate": "2016-05-10"
}, {
"id": 3,
"flightDate": "2016-05-09"
}, {
"id": 4,
"flightDate": "2016-05-08"
}, {
"id": 5,
"flightDate": "2016-05-07"
}]这个json数据每条都是实体,然后输出却是按月份的。
然后页面的展示是这样的:
2016年5月
序号 人名 5月10日
序号 人名 5月09日
序号 人名 5月08日
2016年4月
序号 人名 4月07日
序号 人名 4月06日
序号 人名 4月05日
...
就是说要把这些json数据套在页面上,但是感觉html页面上循环就感觉有点困难,怎么把这个json数据重新排序以便循环输出呢?
我想的是查询出来的时间格式已经是字符串了,用字符串对比判断相同月份,然后来按月份分组,应该怎么做呢?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
var data = [{ "id": 1, "flightDate": "2016-05-11" }, { "id": 2, "flightDate": "2016-05-10" }, { "id": 3, "flightDate": "2016-05-09" }, { "id": 4, "flightDate": "2016-04-08" }, { "id": 5, "flightDate": "2016-04-07" }, { "id": 6, "flightDate": "2016-03-06" }, { "id": 7, "flightDate": "2016-03-05" }]; function getDateArr(arr) { var new_arr = {}; for (var i = 0, len = arr.length; i
想要简单解决就用 lodash 库
var _=require('lodash'); var arr=[{ "id": 1, "flightDate": "2016-05-11" }, { "id": 2, "flightDate": "2016-05-10" }, { "id": 3, "flightDate": "2016-03-09" }, { "id": 4, "flightDate": "2016-04-08" }, { "id": 5, "flightDate": "2016-04-07" }]; var re=_.groupBy(arr,function(item){ return (new Date(item.flightDate).getMonth()); }) console.log(re);输出结果:
{ '2': [ { id: 3, flightDate: '2016-03-09' } ], '3': [ { id: 4, flightDate: '2016-04-08' }, { id: 5, flightDate: '2016-04-07' } ], '4': [ { id: 1, flightDate: '2016-05-11' }, { id: 2, flightDate: '2016-05-10' } ] }现在才看到楼主要原生的实现方法,也可以,
我写一个
var dd = {}; var getM = function (item){ return (new Date(item.flightDate).getMonth()); } arr.forEach(function(value,key){ var keys=getM(value); if(Object.prototype.hasOwnProperty.call(dd,keys)){ dd[keys].push(value); } else { dd[keys] = [value]; } }) console.log(dd);var data = [{ "id": 1, "flightDate": "2016-05-11" }, { "id": 2, "flightDate": "2016-05-10" }, { "id": 3, "flightDate": "2016-05-09" }, { "id": 4, "flightDate": "2016-04-08" }, { "id": 5, "flightDate": "2016-04-07" }, { "id": 6, "flightDate": "2016-03-06" }, { "id": 7, "flightDate": "2016-03-05" }]; var d = []; var a = 0; d[a] = [data[0]]; for(var i=1;i写的有点low,不知道是不是你想要的(前提是你的数据是按时间顺序排列出来的)