简体   繁体   English

node.js用未知键对数字desc排序对象?

[英]nodejs sort object by numeric value desc with unknown keys?

how can i sort this object by value DESC when the keys are unknown? 当键未知时,如何按值DESC排序此对象?

var themen = {"Eisenbahn":2,"Technik":2,"Mathematik":3,"Automobil":4,"Physik":1,"Computer":2,"Ökonomie":1}

Edit: 编辑:

The following codes generates a Map that suits my requirement, unfortunately it cannot be converted to json via JSON.stringify() and just returns {} 以下代码生成了一个适合我要求的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];
}));

any ideas how to make it to json and keep the order? 任何想法如何使其成为json并保持顺序?

Objects have no order, the order in which you add the properties to the object is the order in which they appear. 对象没有顺序,将属性添加到对象的顺序就是它们出现的顺序。

So can build an object based on the first and adding the properties in the order in which you prefer. 因此,可以基于第一个对象构建对象,然后按您喜欢的顺序添加属性。

This works: 这有效:

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
}

So close ... 很近 ...

Change your map line to 将地图线更改为

themen = Object.keys(themen).map(function(v) {
    return [v, themen[v]]
}).sort(function(p,t) {
    return t[1] - p[1];
});

new Map() creates a Map object which is something else. new Map()创建另一个Map对象。

Edit: 编辑:

Unless you want the object again ... 除非您再次想要该对象...

var result = {}
Object.keys(themen).map(function(v) {
    return [v, themen[v]]
}).sort(function(p,t) {
    return t[1] - p[1];
}).forEach(function(v){
    result[v[0]] = v[1];
});
console.log(result); // => sorted object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM