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

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

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

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

当前回答

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

其他回答

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

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

没有多个for循环的排序值(按键排序将排序回调中的索引更改为“0”)

Const list = { “你”:100年, “我”:75年, “foo”:116年, “酒吧”:15 }; let sorted = Object.fromEntries( Object.entries(列表)。排序((a,b) => a[1] - b[1]) ) console.log('已排序对象:',已排序)

我遵循slebetman给出的解决方案(去阅读它的所有细节),但调整,因为你的对象是非嵌套的。

// First create the array of keys/values so that we can sort it:
var sort_array = [];
for (var key in list) {
    sort_array.push({key:key,value:list[key]});
}

// Now sort it:
sort_array.sort(function(x,y){return x.value - y.value});

// Now process that object with it:
for (var i=0;i<sort_array.length;i++) {
    var item = list[sort_array[i].key];

    // now do stuff with each item
}
const arrayOfObjects = [
{name: 'test'},
{name: 'test2'}
]

const order = ['test2', 'test']

const setOrder = (arrayOfObjects, order) =>
    arrayOfObjects.sort((a, b) => {
        if (order.findIndex((i) => i === a.name) < order.findIndex((i) => i === b.name)) {
            return -1;
        }

        if (order.findIndex((i) => i === a.name) > order.findIndex((i) => i === b.name)) {
            return 1;
        }

        return 0;
    });

另一种解决方法:-

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将有结果数组