如果我有一个JavaScript对象,如:

var list = {
  "you": 100, 
  "me": 75, 
  "foo": 116, 
  "bar": 15
};

是否有一种方法可以根据值对属性进行排序?最后得到

list = {
  "bar": 15, 
  "me": 75, 
  "you": 100, 
  "foo": 116
};

当前回答

按值排序对象属性

Const obj ={你:100,我:75,foo: 116, bar: 15}; const keysSorted = Object.keys(obj)。排序((a, b) => obj[a] - obj[b]); Const result = {}; keysSorted。forEach(key => {result[key] = obj[key];}); 文档。write('Result: ' + JSON.stringify(Result));

期望的输出:

{"bar":15,"me":75,"you":100,"foo":116}

引用:

按值排序对象属性 将数组转换为对象

其他回答

另一种解决方法:-

var res = [{"s1":5},{"s2":3},{"s3":8}].sort(function(obj1,obj2){ 
 var prop1;
 var prop2;
 for(prop in obj1) {
  prop1=prop;
 }
 for(prop in obj2) {
  prop2=prop;
 }
 //the above two for loops will iterate only once because we use it to find the key
 return obj1[prop1]-obj2[prop2];
});

//res将有结果数组

输入是对象,输出是对象,使用lodash & js内置库,降序或升序选项,不改变输入对象

Eg输入输出

{
  "a": 1,
  "b": 4,
  "c": 0,
  "d": 2
}
{
  "b": 4,
  "d": 2,
  "a": 1,
  "c": 0
}

实现

const _ = require('lodash');

const o = { a: 1, b: 4, c: 0, d: 2 };


function sortByValue(object, descending = true) {
  const { max, min } = Math;
  const selector = descending ? max : min;

  const objects = [];
  const cloned = _.clone(object);

  while (!_.isEmpty(cloned)) {
    const selectedValue = selector(...Object.values(cloned));
    const [key, value] = Object.entries(cloned).find(([, value]) => value === selectedValue);

    objects.push({ [key]: value });
    delete cloned[key];
  }

  return _.merge(...objects);
}

const o2 = sortByValue(o);
console.log(JSON.stringify(o2, null, 2));

按值排序对象属性

Const obj ={你:100,我:75,foo: 116, bar: 15}; const keysSorted = Object.keys(obj)。排序((a, b) => obj[a] - obj[b]); Const result = {}; keysSorted。forEach(key => {result[key] = obj[key];}); 文档。write('Result: ' + JSON.stringify(Result));

期望的输出:

{"bar":15,"me":75,"you":100,"foo":116}

引用:

按值排序对象属性 将数组转换为对象

我已经用自己的方式尝试过了

var maxSpeed = {
  car: 300, 
  bike: 60, 
  motorbike: 200, 
  airplane: 1000,
  helicopter: 400, 
  rocket: 8 * 60 * 60
};
var sorted = {}
 Object.keys(maxSpeed).sort ((a,b) => maxSpeed[a] - maxSpeed[b]).map(item => sorted[item] = maxSpeed[item]);
console.log(sorted)

以防万一,有人正在寻找保持对象(键和值),使用@Markus R和@James Moran注释的代码引用,只需使用:

var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
var newO = {};
Object.keys(list).sort(function(a,b){return list[a]-list[b]})
                 .map(key => newO[key] = list[key]);
console.log(newO);  // {bar: 15, me: 75, you: 100, foo: 116}