New*_*wtt 3 javascript sorting
我有一个JavaScript对象,如下所示
testObj = {
1/10/2015: {},
2/10/2015: {},
3/10/2015: {},
4/10/2015: {},
29/09/2015: {},
30/09/2015: {}
}
Run Code Online (Sandbox Code Playgroud)
现在,我正在尝试对此进行排序,以便日期按日期按递增顺序排列.为此我完成了以下工作
const orderedDates = {};
Object.keys(testObj).sort(function(a, b) {
return moment(moment(b, 'DD/MM/YYYY') - moment(a, 'DD/MM/YYYY')).format('DD/MM/YYYY');
}).forEach(function(key) {
orderedDates[key] = testObj[key];
})
rangeObj = orderedDates;
Run Code Online (Sandbox Code Playgroud)
然而,这并没有对日期进行排序.它仍然返回与之相同的确切对象testObj.如何根据日期键对对象进行排序?
该行返回一个字符串:
moment(moment(b, 'DD/MM/YYYY') - moment(a, 'DD/MM/YYYY')).format('DD/MM/YYYY')
Run Code Online (Sandbox Code Playgroud)
但sort方法需要一个整数值,因此您需要比较实际日期:
Object.keys(testObj).sort(function(a, b) {
return moment(b, 'DD/MM/YYYY').toDate() - moment(a, 'DD/MM/YYYY').toDate();
}).forEach(function(key) {
orderedDates[key] = testObj[key];
})
Run Code Online (Sandbox Code Playgroud)
但是,您需要注意,在ES5中,规范无法保证对象中键的顺序 - 尽管大多数浏览器都按插入顺序迭代键.但是,在ES6中,您可以保证,如果您迭代对象键,它们将按顺序排列.
因此console.log(orderedDates)可能无法按预期顺序显示密钥,但Object.keys(orderedDates).forEach(function(date) { console.log(date); });可以按预期工作.
var testObj = {
"1/10/2015": {},
"2/10/2015": {},
"3/10/2015": {},
"4/10/2015": {},
"29/09/2015": {},
"30/09/2015": {}
};
var orderedDates = {};
Object.keys(testObj).sort(function(a, b) {
return moment(b, 'DD/MM/YYYY').toDate() - moment(a, 'DD/MM/YYYY').toDate();
}).forEach(function(key) {
orderedDates[key] = testObj[key];
})
Object.keys(orderedDates).forEach(function(date) {
document.body.innerHTML += date + "<br />"
});Run Code Online (Sandbox Code Playgroud)
<script src="http://momentjs.com/downloads/moment.js"></script>Run Code Online (Sandbox Code Playgroud)