0

How to sort JSON object in javascript?

obj = JSON.parse(count);   //count is responseText

and

count= {"MH_YTML":"Yavatmal H.O","MH_WRDH":"Wardha H.O","MH_SWTW":"Sawantwadi H.O"}  //count{key,value}

I want to sort count value(Yavatmal H.O, Wardha H.O and Sawantwadi H.O) by ascending order.

user1745252
  • 19
  • 4
  • 12

3 Answers3

2

JavaScript objects (and their JSON representation, where relevant) have no order. They are unordered bags of property names and values.

You could create an array with entries in a specific order.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

You can't sort an object. However you can create an array and sort it. Something like this:

var count= {"MH_YTML":"Yavatmal H.O", "MH_WRDH":"Wardha H.O", "MH_SWTW":"Sawantwadi H.O"},
    countArr = [];

for (var i in count) {
    countArr.push({key: i, val: count[i]});
}
countArr.sort(function(a, b) {
    if (a.val < b.val) return -1;
    if (a.val > b.val) return 1;
    return 0; 
});

Demo http://jsfiddle.net/dfsq/8S4aD/1/

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • +1 for doing an implementation (though really that's the OP's task), but your `sort` callback is wrong. It needs to return `-1`, `0`, or `1`, not `true` or `false`. – T.J. Crowder Mar 28 '13 at 11:46
  • You've implemented a *reverse* sort, was that your intention? – T.J. Crowder Mar 28 '13 at 11:52
  • @dfsq in `countArr.push({key: i, val: count[i]}); ` for your code its taking key as 1,2,3...so on and for values its taking one single letter as a value "{,M,H,_... so on}". I want here is `key="MH_YTML"` and value should be `value="Yavatmal H.O"` – user1745252 Mar 28 '13 at 12:57
  • @user1745252 Why 1,2,3? `keys` will be `MH_YTML`, `MH_WRDH`, `MH_SWTW`. And values are `Yavatmal H.O`, `Wardha H.O`. Check the fiddle, `console.log(countArr)` to see new structure. – dfsq Mar 28 '13 at 13:01
  • @dfsq I am not able to access fiddle – user1745252 Mar 29 '13 at 09:34
  • Works for me. Doesn't it load or what? – dfsq Mar 29 '13 at 09:36
1

At first convert that object to array, where each array element will be a pair of key & value from object, then sort that array using custom function by values. You can then convert it back to object, but you can't guarantee that object properties order will be kept same.

artahian
  • 2,093
  • 14
  • 17