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

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

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

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

当前回答

    var list = {
    "you": 100,
    "me": 75,
    "foo": 116,
    "bar": 15
};
var tmpList = {};
while (Object.keys(list).length) {
    var key = Object.keys(list).reduce((a, b) => list[a] > list[b] ? a : b);
    tmpList[key] = list[key];
    delete list[key];
}
list = tmpList;
console.log(list); // { foo: 116, you: 100, me: 75, bar: 15 }

其他回答

一个过时问题的后续答案。我写了两个函数,一个是按键排序,另一个是按值排序,并在两个函数中以排序形式返回对象。它也应该在字符串上工作,因为这就是我张贴这个的原因(如果值不是数字的话,上面的一些按值排序有困难)。

const a = { absolutely: "works", entirely: 'zen', best: 'player', average: 'joe' } const prop_sort = obj => { return Object.keys(obj) .sort() .reduce((a, v) => { a[v] = obj[v]; return a; }, {}); } const value_sort = obj => { const ret = {} Object.values(obj) .sort() .forEach(val => { const key = Object.keys(obj).find(key => obj[key] == val) ret[key] = val }) return ret } console.log(prop_sort(a)) console.log(value_sort(a))

我遵循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
}

这里还有一个例子:

函数sortObject(obj) { Var arr = []; var支撑; For (prop in obj) { if (obj.hasOwnProperty(prop)) { arr.push ({ “关键”:道具, “价值”:obj(道具) }); } } 加勒比海盗。排序(函数(a, b) { 返回a.value - b.value; }); 返回arr;//返回数组 } Var列表= { 车:300, 自行车:60岁 摩托车:200, 飞机:1000, 直升机:400, 火箭:8 * 60 * 60 }; var arr = sortObject(list); console.log (arr);

另一种解决方法:-

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

感谢@orad在TypeScript中提供了答案。现在,我们可以在JavaScript中使用下面的代码片断。

function sort(obj,valSelector) { const sortedEntries = Object.entries(obj) .sort((a, b) => valSelector(a[1]) > valSelector(b[1]) ? 1 : valSelector(a[1]) < valSelector(b[1]) ? -1 : 0); return new Map(sortedEntries); } const Countries = { "AD": { "name": "Andorra", }, "AE": { "name": "United Arab Emirates", }, "IN": { "name": "India", }} // Sort the object inside object. var sortedMap = sort(Countries, val => val.name); // Convert to object. var sortedObj = {}; sortedMap.forEach((v,k) => { sortedObj[k] = v }); console.log(sortedObj); //Output: {"AD": {"name": "Andorra"},"IN": {"name": "India"},"AE": {"name": "United Arab Emirates"}}