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

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

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

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

当前回答

如果我有一个这样的对象,

var dayObj = {
              "Friday":["5:00pm to 12:00am"] ,
              "Wednesday":["5:00pm to 11:00pm"],
              "Sunday":["11:00am to 11:00pm"], 
              "Thursday":["5:00pm to 11:00pm"],
              "Saturday":["11:00am to 12:00am"]
           }

我想按天排序,

我们应该先有daySorterMap,

var daySorterMap = {
  // "sunday": 0, // << if sunday is first day of week
  "Monday": 1,
  "Tuesday": 2,
  "Wednesday": 3,
  "Thursday": 4,
  "Friday": 5,
  "Saturday": 6,
  "Sunday": 7
}

初始化一个单独的对象sortedDayObj,

var sortedDayObj={};
Object.keys(dayObj)
.sort((a,b) => daySorterMap[a] - daySorterMap[b])
.forEach(value=>sortedDayObj[value]= dayObj[value])

你可以返回sortedDayObj

其他回答

ES6更新:如果你关心的是有一个排序的对象来迭代(这就是为什么我想象你想要你的对象属性排序),你可以使用Map对象。

您可以按顺序插入(key, value)对,然后执行for..of循环将确保它们按照您插入它们的顺序进行循环

var myMap = new Map();
myMap.set(0, "zero");
myMap.set(1, "one");
for (var [key, value] of myMap) {
  console.log(key + " = " + value);
}
// 0 = zero 
// 1 = one
<pre>
function sortObjectByVal(obj){  
var keysSorted = Object.keys(obj).sort(function(a,b){return obj[b]-obj[a]});
var newObj = {};
for(var x of keysSorted){
    newObj[x] = obj[x];
}
return newObj;

}
var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
console.log(sortObjectByVal(list));
</pre>

@marcusR回答的“箭头”版本供参考

var myObj = { you: 100, me: 75, foo: 116, bar: 15 };
keysSorted = Object.keys(myObj).sort((a, b) => myObj[a] - myObj[b]);
alert(keysSorted); // bar,me,you,foo

更新:2017年4月 返回一个上面定义的排序后的myObj对象。 const myObj ={你:100,我:75,foo: 116, bar: 15}; Const result = 种(myObj) .sort((a, b) => myObj[a] - myObj[b]) .reduce ( (_sortedObj, key) => ({ ……_sortedObj, (例子):myObj(例子) }), {} ); document . write (JSON.stringify(结果));

更新:2021年3月-对象。带有排序功能的条目(根据注释更新) const myObj ={你:100,我:75,foo: 116, bar: 15}; const result =对象 .entries (myObj) .sort((a, b) => a[1] - b[1]) .reduce((_sortedObj, [k,v]) => ({ ……_sortedObj, [k]: v }, {}) document . write (JSON.stringify(结果));

试试这个。即使你的对象没有你试图排序的属性也会被处理。

只需通过发送属性和对象来调用它。

var sortObjectByProperty = function(property,object){

    console.time("Sorting");
    var  sortedList      = [];
         emptyProperty   = [];
         tempObject      = [];
         nullProperty    = [];
    $.each(object,function(index,entry){
        if(entry.hasOwnProperty(property)){
            var propertyValue = entry[property];
            if(propertyValue!="" && propertyValue!=null){
              sortedList.push({key:propertyValue.toLowerCase().trim(),value:entry});  
            }else{
                emptyProperty.push(entry);
           }
        }else{
            nullProperty.push(entry);
        }
    });

      sortedList.sort(function(a,b){
           return a.key < b.key ? -1 : 1;
         //return a.key < b.key?-1:1;   // Asc 
         //return a.key < b.key?1:-1;  // Desc
      });


    $.each(sortedList,function(key,entry){
        tempObject[tempObject.length] = entry.value;
     });

    if(emptyProperty.length>0){
        tempObject.concat(emptyProperty);
    }
    if(nullProperty.length>0){
        tempObject.concat(nullProperty);
    }
    console.timeEnd("Sorting");
    return tempObject;
}

输入是对象,输出是对象,使用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));