The first step is to create a list where each pair (chave,valor)
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 order that list. By default, Javascript sorts arrays first by looking at the first element, then the second, etc. Like dates in the format aaaammdd
can be ordered lexicographically, it is not necessary to use any special parameter in sort
(Edit: according to the update, since the key is a field of the record itself, it is necessary to establish a sort criteria according to - although this 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 only with keys, or only with 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 type library underscore.js, this task can get 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();
You have something like
{"20140101":{ ... }, "20140102":{ ... }, ...}
and wants to return a list containing the objects, this list sorted by date. That’s it?– mgibsonbr
I updated my response to fit your data format. It hasn’t changed much - I just had to add a sort
sort
.– mgibsonbr