Return data from a JSON by ordering from a key

2

I have a JSON file where in the records I have a key that defines a date in the following format: " aaaammdd ". I need to return the existing records in this file but sort them through this key. How would that be?

UPDATE:

this is my file

{
  "241019846088038":{
    "start_time":"20140815",
    "name":"Event 3"
    },
  "244875799004498":{
    "start_time":"20141229",
    "name":"Event 8"
    },
  "288519758006296":{
    "start_time":"20140809",
    "name":"Event 1"
    }      ,
  "576146455831402":{
    "start_time":"20140830",
    "name":"Event 14"
    }
  ,
  "1416493345292145":{
    "start_time":"20140920",
    "name":"Event 2"
    }
}
    
asked by anonymous 17.07.2014 / 06:58

1 answer

1

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();
    
17.07.2014 / 08:15