简体   繁体   English

按日期值对JSON对象进行排序

[英]Sort JSON Object by date value

I have an object in javascript 我在javascript中有一个对象

Object {HIDDEN ID: "06/03/2014", HIDDEN ID: "21/01/2014"}

I want to be able to create a new object that will have it sorted by recent date. 我希望能够创建一个新对象,并将其按最近日期排序。

Like so: 像这样:

SortedObject {"HIDDEN ID" : "21/01/2014", "HIDDEN ID" : "06/03/2014"}

I know how I could achieve this with an array but I dont know how to iterate through objects to sort by date. 我知道如何用数组来实现这一点,但是我不知道如何遍历对象以按日期排序。

Any help is much appreciated 任何帮助深表感谢

EDIT: 编辑:

Now I Have this code. 现在我有了这段代码。

for(var x=0; x<folderList.length; x++){
                    retrieveAllFilesInFolder(folderList[x], function(){
                        var arr = []; 
                        for(var i in fileListObj) { 
                           var d = fileListObj[i].split("/");
                           arr.push({"id": i, "date":(new Date(d[2],d[1]-1,d[0]))}); 
                        }
                        arr.sort(function(a,b) { return a.date < b.date;});
                        console.log(arr); 
                    });
                }

However my output is not sorted bydate. 但是我的输出没有按日期排序。

Object 1 id: "hiddenID1", date: Mon Nov 18 2013 00:00:00 GMT+0000 (GMT Standard Time)
Object 2 id: "hiddenId2", date: Thu Mar 06 2014 00:00:00 GMT+0000 (GMT Standard Time)
Object 3 id: "hiddenId3", date: Thu Sep 05 2013 00:00:00 GMT+0100 (GMT Daylight Time)

You cant sort an object as it contains key value pairs & not serialized items. 您无法对对象进行排序,因为它包含键值对和未序列化的项目。

You must first construct an array & then sort it. 您必须首先构造一个数组,然后对其进行排序。

var obj = {"a" : "21/01/2014", "b" : "06/03/2014"};

var arr = []; 

for(var i in obj) { 

   var d = obj[i].split("/"); 

   arr.push({"id": i, "date":(new Date(d[2],d[1]-1,d[0]))}); 
}

arr.sort(function(a,b) { return a.date.valueOf() > b.date.valueOf();});

The result will be a an array arr sorted by date. 结果将是一个按日期排序的数组arr

you can't "sort" JSON objects; 您不能“排序” JSON对象; the only thing you could do would be to get the values into an array and sort the array. 您唯一可以做的就是将值放入数组并对数组进行排序。 i assume the two "hidden id"'s are two distinct fields because your example is not valid JSON. 我假设两个“隐藏ID”是两个不同的字段,因为您的示例不是有效的JSON。

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

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