您可以将数据复制到数组中,然后对其进行排序:
var data = {
a : {
timestamp: 11111,
other : "xxx"
},
b : {
timestamp: 22222,
other : "yyy"
},
c : {
timestamp: 33333,
other : "zzz"
}
};
var output = [];
// copy items to an array so they can be sorted
for (var key in data) {
data[key].key = key; // save key so you can access it from the array (will modify original data)
output.push(data[key]);
}
output.sort(function(a,b) {
return(a.timestamp - b.timestamp);
});
生成它作为输出(请注意,我将原始密钥添加到对象中,以便可以从数组访问它):
[{"timestamp":11111,"other":"xxx","key":"a"},
{"timestamp":22222,"other":"yyy","key":"b"},
{"timestamp":33333,"other":"zzz","key":"c"}]
你可以在这里看到它的工作原理:http://jsfiddle.net/jfriend00/hXpkP/ http://jsfiddle.net/jfriend00/hXpkP/