本文介绍了在javascript中对嵌套对象的对象进行排序(也许使用lodash?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套对象的对象,并想按嵌套值之一进行排序(例如,"month_sales"降序排列).数据如下所示:

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, 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 }
}

这就是我想要的样子(按month_sales降序排列):

This is what I want it to look like (sort by month_sales descending):

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

我遍历了Google和StackOverflow,只找到了几个有关对对象而不是数组进行排序的答案,并且在每种情况下,答案都是写一个函数来转换对象"到一个数组中,对它进行排序,然后将其变回一个对象."

I have looked all over Google and StackOverflow, and have only found a couple answers that deal with sorting an object rather than an array, and in every case the answer has been along the lines of "write a function to convert the object to an array, sort that, and then turn it back into an object."

作为最后的手段,我愿意这样做,但似乎我应该能够做到这一点,而无需解构整个对象并将其重新放回原处.也许有一种优雅的方法可以在lodash或其他方式中做到这一点?

I'm willing to do that as a last resort, but it seems like I should be able to do this without deconstructing the entire object and putting it back together again. Maybe there's an elegant way to do this in lodash or something?

推荐答案

您只能拥有已排序的数组,而不能拥有对象.为此,您首先需要将对象映射到数组.使用lodash map() sortBy():

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 }
// ]

该映射使用 defaults()函数为每个数组项赋予新的name属性,用于对数组进行排序.

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

这篇关于在javascript中对嵌套对象的对象进行排序(也许使用lodash?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 13:01