按值对地图/哈希进行排序,并保留键 [英] Sort Map/Hash by values, retaining keys

查看:97
本文介绍了按值对地图/哈希进行排序,并保留键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真想找一个答案了.

我想在JavaScript中有一个哈希,就像这样:

I would like to have a hash in JavaScript, like so:

const hash = {
   a: 'A',
   c: 'C',
   b: 'B'
}

,我想按 对对象进行排序,以使它可能变为:

and I would like to sort the object by the value, such that it might become:

const hash = {
   a: 'A',
   b: 'B',
   c: 'C',
}

现在,我意识到POJSO不能保证其键的顺序,因此我在考虑使用immutableJS或某种可以保证哈希中键的顺序的对象.

now, I realize that POJSOs don't guarantee the order of their keys, so I was thinking of using immutableJS or some object that will guarantee the order of the keys in the hash.

所以我正在寻找类似的东西:

so I am looking for something like:

var newHash = Immutable.Map(hash).sortBy(function(key,val){
       return val;
});

但是我不相信这存在. 这太多了吗?如何找到此功能?

But I don't believe this exists. is this too much to ask? How can I find this functionality?

推荐答案

Lodash单线:

sorted = _(hash).toPairs().sortBy(1).fromPairs().value();

实时示例:

var data = {a: 'A', c: 'C', b: 'B'};
var hash = _(data).toPairs().sortBy(1).fromPairs().value();
Object.getOwnPropertyNames(hash).forEach(n => {
  snippet.log("hash['" + n + "'] = " + hash[n]);
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

这篇关于按值对地图/哈希进行排序,并保留键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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