Akhil Mahindrakar Akhil Mahindrakar - 3 months ago 22
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

input:

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


output:

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

mmm mmm
Answer

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