Akhil Mahindrakar Akhil Mahindrakar - 1 year ago 86
JSON Question

How to sort Json?

How to sort array containing JSON's based on the number of keys in each object in ascending order?

program in javascript


[{a : 'a', b : 'b'}, {a : 'a'}, {a : 'a', b : 'b', c : 'c'}]


[{a : 'a'}, {a : 'a', b : 'b'}, {a : 'a', b : 'b', c : 'c'}]

mmm mmm
Answer Source

Just sort it by the Object's keys length:

var arr = [{a : 'a', b : 'b'}, {a : 'a'}, {a : 'a', b : 'b', c : 'c'}];
var res = arr.sort(function(a,b) {
    return Object.keys(a).length - Object.keys(b).length;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download