用lodash按值对对象排序

用lodash按值对对象排序

本文介绍了用lodash按值对对象排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的对象:

var unsorted = {a: 15, b: 1,c: 2, d: 4, e: 3, f: 6, g: 1}

我感兴趣的是用lodash按降序对它进行排序,因此预期结果应该是:

var sortd = {b: 1, g: 1,c: 2, e: 3, d: 4, f: 6, a: 15}

我尝试过使用lodash orderBy,但是它只给出了排序后的值组成的数组.

_.orderBy(tempCount, Number, ['desc'])

//Result
[1,1,2,3,4,6,15]
解决方案

您可以使用已排序的键/值对构建新对象.

实际标准或属性顺序:

  • 首先对键之类的索引进行排序
  • 按插入顺序保留所有其他键

要完全控制订单,请使用带有键的数组,并将其作为值的排序访问器.

 var unsorted = { a: 15, b: 1,c: 2, d: 4, e: 3, f: 6, g: 1 },
    sorted = _(unsorted)
        .toPairs()
        .orderBy([1], ['desc'])
        .fromPairs()
        .value()

console.log(sorted); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script> 

通过使用特定参数的最后一个参数,对 _.orderBy 进行降序排序顺序,而不是 _.sortBy ,它仅允许升序排序.

 var unsorted = { a: 15, b: 1,c: 2, d: 4, e: 3, f: 6, g: 1 },
    sorted = _(unsorted)
        .toPairs()
        .orderBy(1, 'desc')
        .fromPairs()
        .value()

console.log(sorted); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script> 

I have an object that looks like this:

var unsorted = {a: 15, b: 1,c: 2, d: 4, e: 3, f: 6, g: 1}

And I am interested in sorted it in descending order with lodash, so the expected result should be:

var sortd = {b: 1, g: 1,c: 2, e: 3, d: 4, f: 6, a: 15}

I have tried using lodash orderBy but it gives an array of just the values sorted.

_.orderBy(tempCount, Number, ['desc'])

//Result
[1,1,2,3,4,6,15]
解决方案

You could build a new object with the sorted key/value pairs.

The actual standard or the order of properties:

  • sort index like keys first, in order
  • keep all other keys in insertation order

For a complete control over the order, take an array with the keys an take it as sorted accessor for the values.

var unsorted = { a: 15, b: 1,c: 2, d: 4, e: 3, f: 6, g: 1 },
    sorted = _(unsorted)
        .toPairs()
        .orderBy([1], ['desc'])
        .fromPairs()
        .value()

console.log(sorted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Descending sort with _.orderBy by using a the last parameter for a specific order, instead of _.sortBy, which only allows to sort ascending.

var unsorted = { a: 15, b: 1,c: 2, d: 4, e: 3, f: 6, g: 1 },
    sorted = _(unsorted)
        .toPairs()
        .orderBy(1, 'desc')
        .fromPairs()
        .value()

console.log(sorted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

这篇关于用lodash按值对对象排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 00:36