chrissavage chrissavage - 3 months ago 10
Javascript Question

Sort Array Of Objects By Number of Keys (JavaScript)

Hi all I have an array of objects (20 of them) that I've placed in this format to make columns in an Angular Project (note there are objects in objects). I want to sort them by object with most keys (inside each object in array), to object with least number keys inside object in array) so that when they are displayed in columns it makes the most sense.

I'm mutating a navbar variable to use for a clickable advanced search. Thanks for the help as this is my first big project as a new developer.



var clickableFilters = [
{"State": {
"0": [{value: "liquid"}, {count: 30}]
}
},
{"Country": {
"0": [{value: "USA"}, {count: 50}]
"1": [{value: "Nigeria"}, {count: 90}]
}
},
{"Color": {
"0": [{value: "blue"}, {count: 30}]
"1": [{value: "purple"}, {count: 50}]
"2": [{value: "green"}, {count: 100}]
}
}
]





How do I sort the objects by number of Keys (keys in inner object) so that it ends up (in JavaScript)

[{"Color": {}}, {"Country": {}}, {"State": {}}]

Answer

For your data structure you can use sort() like this.

var arrayOfObjects = [
  {"least#OfKeysObject": {
    key1: 'value',
    }
  },
  {"secondMost#OfKeysObj": {
    key1: 'value',
    key2: 'value'
    }
  },
  {"most#OfKeysObj": {
    key1: 'value',
    key2: 'value',
    key3: 'value'
    }
  }
 ];
 
 var result = arrayOfObjects.sort(function(a, b) {
   return Object.keys(b[Object.keys(b)[0]]).length - Object.keys(a[Object.keys(a)[0]]).length;
 });
 
 console.log(result)