按值对对象属性进行排序 [英] Sorting object property by values

查看:83
本文介绍了按值对对象属性进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have a JavaScript object such as:

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

是否有一种基于值对属性进行排序的方法?这样我就结束了

Is there a way to sort the properties based on value? So that I end up with

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

推荐答案

将它们移至数组,对该数组进行排序,然后将其用于您的目的.这是一个解决方案:

Move them to an array, sort that array, and then use that array for your purposes. Here's a solution:

var maxSpeed = {
    car: 300, 
    bike: 60, 
    motorbike: 200, 
    airplane: 1000,
    helicopter: 400, 
    rocket: 8 * 60 * 60
};
var sortable = [];
for (var vehicle in maxSpeed) {
    sortable.push([vehicle, maxSpeed[vehicle]]);
}

sortable.sort(function(a, b) {
    return a[1] - b[1];
});

//[["bike", 60], ["motorbike", 200], ["car", 300],
//["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]


一旦有了数组,就可以按照自己喜欢的顺序从数组中重建对象,从而完全实现您打算要做的事情.在我所知道的所有浏览器中都可以使用,但这取决于实现的怪癖,并且可能随时中断.您永远不要假设JavaScript对象中元素的顺序.


Once you have the array, you could rebuild the object from the array in the order you like, thus achieving exactly what you set out to do. That would work in all the browsers I know of, but it would be dependent on an implementation quirk, and could break at any time. You should never make assumptions about the order of elements in a JavaScript object.

var objSorted = {}
sortable.forEach(function(item){
    objSorted[item[0]]=item[1]
})

这篇关于按值对对象属性进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆