Return data from a JSON by sorting from a key

Asked

Viewed 883 times

2

I have a JSON file where in the records I have a key that defines a date in the following format: "yyyymmdd". 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"
    }
}
  • You have something like {"20140101":{ ... }, "20140102":{ ... }, ...} and wants to return a list containing the objects, this list sorted by date. That’s it?

  • I updated my response to fit your data format. It hasn’t changed much - I just had to add a sort sort.

1 answer

1

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();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.