Lodash按值对对象排序,而不会丢失键 [英] Lodash sorting object by values, without losing the key

查看:129
本文介绍了Lodash按值对对象排序,而不会丢失键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个对象:

{Derp: 17, Herp: 2, Asd: 5, Foo: 8, Qwe: 12}

我需要按值对它进行排序.我想要得到的是:

And I need to sort it by value. What I'm looking to get is:

{Derp: 17, Qwe: 12, Foo: 8, Asd: 5, Herp: 2}

我想使用lodash.当我使用_.sortBy时,它不会保留任何键:

I'd like to use lodash for it. When I use _.sortBy it doesn't retain the keys how ever:

_.sortBy({Derp: 17, Herp: 2, Asd: 5, Foo: 8, Qwe: 12}).reverse();
// [17, 12, 8, 5, 2]

地狱,我什至只满足于键数组,但仍然按输入中的值排序:

Hell, I'd even settle for just the array of keys, but still sorted by the value in the input:

['Derp', 'Herp', 'Foo', 'Asd', 'Qwe']

推荐答案

您可以尝试这样,

_.mapValues(_.invert(_.invert(obj)),parseInt);

对象{Herp:2,Asd:5,Foo:8,Qwe:12,Derp:17}

Object {Herp: 2, Asd: 5, Foo: 8, Qwe: 12, Derp: 17}

var obj = {Derp: 17, Herp: 2, Asd: 5, Foo: 8, Qwe: 12}

var result = _.reduceRight(_.invert(_.invert(obj)), function(current, val, key){    
    current[key] = parseInt(val);
    return current;
},{});

对象{Derp:17,Qwe:12,Foo:8,Asd:5,Herp:2}

Object {Derp: 17, Qwe: 12, Foo: 8, Asd: 5, Herp: 2}

或 使用Chain方法:

or Using Chain methods:

_.chain(obj).invert().invert().reduceRight(function(current, val, key){ 
    current[key] = parseInt(val);
    return current;
},{}).value()

对象{Derp:17,Qwe:12,Foo:8,Asd:5,Herp:2}

Object {Derp: 17, Qwe: 12, Foo: 8, Asd: 5, Herp: 2}

注意:在大多数情况下,通常不取决于浏览器的对象属性顺序.

Note: It depends on browser usally object properties order is not gurrantee in most case.

这篇关于Lodash按值对对象排序,而不会丢失键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆