0

I have a very simple json object,

{
   "costA": 9617,
   "costB": 11100,
   "costC": 13208,
   "costD": 9910
}

Is it possible to sort this json (in javascript) to get the resultant?

{
   "costA": 13208,
   "costB": 11100,
   "costC": 9910,
   "costD": 9617
}

Note: key names can change..

painotpi
  • 6,894
  • 1
  • 37
  • 70

1 Answers1

0

The below JavaScript gives the result you're after: {costA: 13208, costB: 11100, costC: 9910, costD: 9617}:

var obj = JSON.parse('{"costA": 9617, "costB": 11100, "costC": 13208, "costD": 9910}');
var values = [], keys = [], key, i;
for (key in obj) {
    keys.push(key);
    values.push(obj[key]);
}
values.sort(function (a, b) { return b-a; });
keys.sort();
for (i = 0; i < keys.length; ++i) {
    key = keys[i];
    val = values[i];
    obj[key] = val;
}

console.log(obj);

See also fiddle.

aknuds1
  • 65,625
  • 67
  • 195
  • 317