当键未知时,如何按值 DESC 对该对象进行排序?
var themen = {"Eisenbahn":2,"Technik":2,"Mathematik":3,"Automobil":4,"Physik":1,"Computer":2,"Ökonomie":1}
编辑:
下面的代码生成了一个符合我要求的Map,不幸的是它无法通过JSON.stringify()转换为json,只能返回{}
themen = new Map(Object.keys(themen).map(function(v) {
return [v, themen[v]]
}).sort(function(p,t) {
return t[1] - p[1];
}));
有什么想法如何将其转换为 json 并保持顺序吗?
最佳答案
对象没有顺序,向对象添加属性的顺序就是它们出现的顺序。
因此,可以基于第一个对象构建一个对象,并按照您喜欢的顺序添加属性。
这有效:
var orderThemen = function (themen) {
var themens = Object.keys(themen)
var order = {}
var output = {}
themens.forEach(function (key) {
var auxThemen = themen[key]
if (!order[auxThemen]) order[auxThemen] = []
order[auxThemen].push(key)
})
Object.keys(order).forEach(function (key) {
var level = order[key]
level.forEach(function (themen) {
output[themen] = key
})
})
return output
}
关于javascript - nodejs 按未知键的数值 desc 对对象进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36104492/