排序JSON数组按日期键 [英] Sort JSON array by date key
问题描述
我有一个JSON数组和我想的排序是按日期之前,我追加了。
该数组看起来这样的:
结果= [];
result.push(
{ID:'ID',结果是:{URL:测试,日期:'15 2013年5月,6:40 PM'}},
{ID:'ID',结果是:{URL:测试,日期:'20 2012年12月,上午8:00'}},
{ID:'ID',结果是:{URL:测试,日期:1929 2012年6月,下午5:47'}}
);
目前,我设法数组排序日期这样的:
VAR datearray = [
2011-05-26 12:00:00,
2016年1月26日12:00:00,
2011-01-26 12:00:00,
2012年12月8日07:00:00,
2011-01-26 12:00:00,
1995年1月5日06:00:00
];datearray.sort();
这给了我:
1995年1月5日06:00:00
2011-01-26 12:00:00
2011-01-26 12:00:00
2011-05-26 12:00:00
2012年12月8日07:00:00
2016年1月26日12:00:00
但林不知道如何为一个复杂的阵列包含不止一个按键做同样的。我知道的我应该首先格式化日期YYYY-MM-DD 的但经过IM还挺搞砸了。
有一个良好的开端是从我现在来到了上jsbin发现:的http:// jsbin。 COM / ipatok / 8 /编辑
函数补偿(A,B){
返回新的日期(a.result.date).getTime() - 新的日期(b.result.date).getTime();
}your_array.sort(化合物);
只是为了延长@ Karthikr的评论。
下面是的jsfiddle
I have a json array and I am trying to sort it by date before I append it.
The array looks as such:
result = [];
result.push(
{id: 'ID', result: {url: 'test', date: '15 May 2013, 6:40 pm'}},
{id: 'ID', result: {url: 'test', date: '20 Dec 2012, 8:00 am'}},
{id: 'ID', result: {url: 'test', date: '29 Jun 2012, 5:47 pm'}}
);
Currently, I have managed to sort an array of dates as such:
var datearray = [
'2011-05-26 12:00:00',
'2016-01-26 12:00:00',
'2011-01-26 12:00:00',
'2012-12-08 07:00:00',
'2011-01-26 12:00:00',
'1995-01-05 06:00:00'
];
datearray.sort();
which gives me:
1995-01-05 06:00:00
2011-01-26 12:00:00
2011-01-26 12:00:00
2011-05-26 12:00:00
2012-12-08 07:00:00
2016-01-26 12:00:00
but Im not sure how to do the same for a complex array which contains more keys than one. I know that I should firstly format the date to YYYY-MM-DD but after im kinda messed up.
A good start would be from what I currently came up with found on jsbin: http://jsbin.com/ipatok/8/edit
function comp(a, b) {
return new Date(a.result.date).getTime() - new Date(b.result.date).getTime();
}
your_array.sort(comp);
Just to extend @Karthikr's comment.
Here is jsfiddle
这篇关于排序JSON数组按日期键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!