The first step is to create a list where each (chave,valor)
pair is represented by an array:
var jsonDecoded = { "241019846088038":{ "start_time":"20140815", "name":"Event 3" }, ... };
var pares = [];
for ( var p in jsonDecoded )
pares.push([p, jsonDecoded[p]]);
// pares == [ ["241019846088038",{ "start_time":"20140815", "name":"Event 3" }], ... ]
Then you can sort this list. By default, JavaScript sorts arrays by first looking at the first element, then the second, and so on. Because dates in the format aaaammdd
can be ordered lexicographically, it is not necessary to use any special parameters in sort
: according to update, as the key is a field of the record itself, it is necessary to establish a sort order of agreement - even if that criterion benefits from the format used):
function compararDatas(a, b) {
return a[1].start_time < b[1].start_time ? -1 :
a[1].start_time > b[1].start_time ? 1 : 0;
}
pares.sort(compararDatas);
If you want, you can then get an array with only the keys, or just the values:
var chaves = [];
var valores = [];
for ( var i = 0 ; i < pares.length ; i++ ) {
chaves[i] = pares[i][0];
valores[i] = pares[i][1];
}
Example in jsFiddle .
This is a solution using pure JavaScript. If you have access to a underscore.js library, this task can be a lot easier:
var pares = _.pairs(jsonDecoded).sort(compararDatas);
var chaves = _.pluck(pares, 0);
var valores = _.pluck(pares, 1);
Example in jsFiddle . If you are only interested in the values of the records (and not the keys), then you can do it in a single line:
var valores = _.chain(jsonDecoded).pairs().sort(compararDatas).pluck(1).value();