JavaScript Snippet - Object Sort

Posted at

This is straightforward (but memory-efficient) Object ("JSON"-like) recursive sort.
It can handle both Arrays And Objects.

function sort_object(obj){ /* json like */
var result = {};

Object.keys(obj).sort().forEach(function(key){
key = String(key);
result[key] = obj[key];
});

return result;
}

function is_object(a){
return "object" === typeof a &&
"object" === a.constructor.name.toLowerCase()
}

function is_array(a){
return "object" === typeof a &&
"array" === a.constructor.name.toLowerCase()
}

function sorter(a){
/* nothing to sort (2 cases) */
if(null === a) return a;
if(false === is_object(a) &&
false === is_array(a)) return a;

a = true === is_object(a) ? sort_object(a) :
true === is_array(a) ? a.sort() :
a /* will not arrive here.. */
;

Object.keys(a).forEach(function(aa){
a[aa] = sorter(a[aa]);
});

return a;
}





before:
{
    "b": {
      "g": 0
    , "z": 0
    , "a": 0
  }
  , "c": [4, 9, 1, 0]
  , "a": "hi"
}


after:
{
    "a": "hi"
  , "b": {
      "a": 0
    , "g": 0
    , "z": 0
  }
  , "c": [0, 1, 4, 9]
}