2015-09-04 114 views
2

我有一個JavaScript對象,看起來像如下基於日期鍵排序JavaScript對象

testObj = { 
    1/10/2015: {}, 
    2/10/2015: {}, 
    3/10/2015: {}, 
    4/10/2015: {}, 
    29/09/2015: {}, 
    30/09/2015: {} 
} 

現在,我想解決這使得日期按日期按升序排列。爲此,我做了以下工作

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; 

但是,這並不排序日期。它仍然返回與testObj相同的確切對象。如何根據日期鍵對對象進行排序?

+0

這裏的答案http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – mguimard

+0

@mguimard但使用const'的'將指示[ES6](http://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties),而不是ES5 – CodingIntrigue

回答

5

此行返回字符串

moment(moment(b, 'DD/MM/YYYY') - moment(a, 'DD/MM/YYYY')).format('DD/MM/YYYY') 

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]; 
}) 

要知道,在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 />" 
 
});
<script src="http://momentjs.com/downloads/moment.js"></script>