按属性值排序JavaScript对象 [英] Sorting JavaScript Object by property value

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

问题描述

如果我有一个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.

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

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