按JS中的值对嵌套字典进行排序 [英] Sort nested dictionary by value in JS
问题描述
有人可以帮忙找出用JavaScript里面的另一个字典对字典进行排序的方法吗?这是我的字典的样子:
Can someone please help to figure out the way to sort a dictionary with another dictionary inside in JavaScript? This is how my dict looks like:
{'POS2':{'stegano':0,'sum':200,'misc':100,'web':0,'ppc':0,'crypto':0,'admin':0,'vuln':0,'取证':0,'硬件':0,'反向':0,'侦察':100},...}
我想通过存储在嵌套字典中的"sum"键对它进行排序.我可以找到一些用python编写的解决方案,但是这里的挑战是要在JS中实现相同的功能.不胜感激.
I want to sort it by 'sum' key that is stored in nested dict. I can find some solutions written in python, but the challenge here is to achieve the same functionality in JS. Would appreciate any help.
推荐答案
只需使用 Object.values
检索内部对象,然后使用 Array.sort
对其进行排序内容.请注意,您无法对对象属性进行排序,因为它们默认情况下是未排序的集合(或者至少没有正确描述应如何在对象上对属性进行排序)
Just retrieve the inner object using Object.values
and then use Array.sort
to sort by it's content. Note that you cannot sort an objects properties as they are per default an unsorted set (or at least, it's not properly described how properties should be sorted on an object)
const dict = {
'POS2': {
'stegano': 0,
'sum': 200,
'misc': 100,
'web': 0,
'ppc': 0,
'crypto': 0,
'admin': 0,
'vuln': 0,
'forensics': 0,
'hardware': 0,
'reverse': 0,
'recon': 100
},
'POS1': {
'sum': 100
},
'POS3': {
'sum': 250
}
};
function orderBySubKey( input, key ) {
return Object.values( input ).map( value => value ).sort( (a, b) => a[key] - b[key] );
}
console.log( orderBySubKey( dict, 'sum' ) );
此示例将删除外部属性,如果要保留这些属性,则可以稍微更改顺序,例如
This sample would remove the outer properties, if you want to keep these, you can change your ordering a bit, for example like
const dict = {
'POS2': {
'stegano': 0,
'sum': 200,
'misc': 100,
'web': 0,
'ppc': 0,
'crypto': 0,
'admin': 0,
'vuln': 0,
'forensics': 0,
'hardware': 0,
'reverse': 0,
'recon': 100
},
'POS1': {
'sum': 100
},
'POS3': {
'sum': 250
}
};
function orderBySubKey( input, key ) {
return Object.keys( input ).map( key => ({ key, value: input[key] }) ).sort( (a, b) => a.value[key] - b.value[key] );
}
console.log( orderBySubKey( dict, 'sum' ) );
这会给您带来不同的输出,但仍然可以让您在原始字典中查找
Which gives you a different output, but would still allow you to lookup inside the original dictionary
这篇关于按JS中的值对嵌套字典进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!