如何按关键日期对对象进行排序?

时间:2019-02-18 13:59:14

标签: javascript

我有以下对象:

   var obj = {
  "2019-01-28 00:00:00.000": [],
  "2019-01-29 00:00:00.000": [],
  "2019-01-30 00:00:00.000": [],
  "2019-02-02 00:00:00.000": []
}

如何按键/日期对该对象排序?

我尝试遍历所有元素并转换为new Date(element),然后与上一个值进行比较。

2 个答案:

答案 0 :(得分:2)

键的顺序在javascript中不固定。您可以提取键,对键进行排序,然后为每个键运行一个函数

var objKeys = Object.keys(obj);
objKeys.sort();
objKeys.forEach( (value) => {
    // do something with obj[value]
});

答案 1 :(得分:1)

您可以使用此:

var keys= Object.keys(obj).sort(function(a,b){
    // Probably you cast the Date applying a new Date()
    // Also you can use > to order DESC
    // You can create a function to order ASC or DESC
    return a<b;
});

// Now you could iterate your object ordered
keys.foreach(function(k) {
    // This your fist element ordered obj[k]
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort