Skip to content Skip to sidebar Skip to footer

Sorting An Object Of Nested Objects In Javascript (maybe Using Lodash?)

I have an object of nested objects and would like to sort by one of the nested values (e.g. 'month_sales' descending). This is what the data looks like: { 'Bob': { sales: 13, reve

Solution 1:

You can only have sorted arrays, not objects. To do that, you first need to map your object to an array. Here's how you can do it using lodash map() and sortBy():

_(data).map(function(value,key) {
        return_.defaults({ name:key }, value);
    }).sortBy('name').value();//// [
//   { name:"Bill", today_sales:20, week_sales:38, month_sales:186 },
//   { name:"Bob", sales:13, revenue:33, month_sales:149 },
//   { name:"Jane", today_sales:17, week_sales:38, month_sales:164 }
// ]

The mapping uses the defaults() function to give each array item a new name property, which is used to sort the array.

Solution 2:

This is not possible because properties of objects do not have a guaranteed order in javascript. You will have to convert it to an array perhaps like this first:

[ 
  { name:"Bob", sales:13, revenue:33, month_sales:149 },
  { name:"Bill", today_sales:20, week_sales:38, month_sales:186 },
  { name:"Jane", today_sales:17, week_sales:38, month_sales:164 }
]

Then when you sort it as an array it will maintain that order.

Solution 3:

If you convert your object to an array, then you could sort them by category like this

var arr = [ 
  { name: "Bob", sales: 13, revenue: 33, month_sales: 149 },
  { name: "Bill", today_sales: 20, week_sales: 38, month_sales: 186 },
  { name: "Jane", today_sales: 17, week_sales: 38, month_sales: 164 }
]

arr.sort(function(x, y){
    var category = "month_sales"if (x[category] < y[category]) {
        return -1;
    }
    if (x[category] > y[category]) {
        return1;
    }
    return0;
});

Solution 4:

While you can't sort an object, you can create an index sorted on whatever property you want, e.g. to get a list of the names sorted by month_sales highest to lowest:

varobj= { 
"Bob": { sales:13, revenue:33, month_sales:149 },
"Bill": { today_sales:20, week_sales:38, month_sales:186 },
"Jane": { today_sales:17, week_sales:38, month_sales:164 }
}

varindex=Object.keys(obj).sort(function(a,b) {
              returnobj[b].month_sales-obj[a].month_sales;
            });

Then get the one with the highest value:

console.log(index[0] + ':' + obj[index[0]].month_sales); // Bill:186

Post a Comment for "Sorting An Object Of Nested Objects In Javascript (maybe Using Lodash?)"