简体   繁体   English

根据日期键对javascript对象进行排序

[英]Sort javascript object based on date keys

I have a JavaScript object that looks like follows我有一个如下所示的 JavaScript 对象

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

Now, I'm trying to sort this such that the dates are arranged by date in increasing order.现在,我正在尝试对此进行排序,以便日期按日期按递增顺序排列。 For that i've done the following为此,我做了以下工作

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;

This however is not sorting the dates at all.然而,这根本不是对日期进行排序。 It still returns the same exact object as testObj .它仍然返回与testObj完全相同的对象。 How do I sort the object based on date keys?如何根据日期键对对象进行排序?

This line returns a string :这一行返回一个字符串

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

But the sort method requires an integer value, so you need to compare the actual dates instead:但是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];
})

However you need to be aware that in ES5, the order of keys in an object was not guaranteed by the spec - although most browsers did iterate the keys in insertion order.但是,您需要注意,在 ES5 中,对象中键的顺序不受规范保证 - 尽管大多数浏览器确实按插入顺序迭代键。 In ES6 however, you can be guaranteed that if you iterate your objects keys they will be in order.然而,在 ES6 中,你可以保证,如果你迭代你的对象键,它们将是有序的。

So console.log(orderedDates) may not show the keys in your expected order, but Object.keys(orderedDates).forEach(function(date) { console.log(date); });所以console.log(orderedDates)可能不会按照你预期的顺序显示键,但是Object.keys(orderedDates).forEach(function(date) { console.log(date); }); will work as expected.将按预期工作。

 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>

Without moment library you can also do. It will work for all js framework

var testObj = {
  "3/10/2015": {},
  "2/10/2015": {},
  "1/10/2015": {},
  "4/10/2015": {},
  "29/09/2015": {},
  "30/09/2015": {}
};
var ordered = {};
Object.keys(testObj).sort(function(a, b) {
  return (dateConverter(a) - dateConverter(b));
}).forEach(function(key) {
  ordered[key] = testObj[key];
});

/* Convert DD/MM/YY to date object */
function dateConverter(date) {
  var dateParts = date.split("/");
  var dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]); 
  return dateObject
}
/* ordered return now                                               
  "1/10/2015": {},
  "2/10/2015": {},
  "3/10/2015": {},
  "4/10/2015": {},
  "29/09/2015": {},
  "30/09/2015": {} */

Without moment, easier sorting can be achieved if the date is in the format 'YYYYMMDD' with any separator.如果日期采用带有任何分隔符的“YYYYMMDD”格式,则无需片刻,可以实现更轻松的排序。

 const 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 a.split('/').reverse().join('').localeCompare(b.split('/').reverse().join('')); }).forEach(function(key) { orderedDates[key] = testObj[key]; }) console.log(orderedDates);

Using the moment package, you can use:使用moment包,您可以使用:

const yourFormat = 'DD/MM/YYYY'
const sortDateMoments = (dates) => {
  const moments = dates.map(date => moment(date, yourFormat))
  moments.sort((a, b) => a.isBefore(b) ? 1 : -1)
  return moments
}

this can be achieved without using moment, console.log() could still mess up the order but iterating the keys would work like a charm, Yeah perks of ES5.这可以在不使用 moment 的情况下实现, console.log()仍然可能会弄乱顺序,但是迭代键会像魅力一样工作,是的 ES5 特权。

 const sortDatesObject = (unsortedDatesObject) => { const sortedObject = {}; const reverseDate = date => date.split('/').reverse().join('/'); Object.keys(unsortedDatesObject) .map(date => reverseDate(date)) .sort((a, b) => { return new Date(a) - new Date(b) }) .forEach((date) => { sortedObject[reverseDate(date)] = unsortedDatesObject[reverseDate(date)] }); return sortedObject; } testObj = { "1/10/2015": {}, "2/10/2015": {}, "3/10/2015": {}, "4/10/2015": {}, "29/09/2015": {}, "30/09/2015": {} } Object.keys(sortDatesObject(testObj)).forEach(key => console.log(key));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM