Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

javascript - 按值对对象属性进行排序(Sorting object property by values)

If I have a JavaScript object such as:

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

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
};
  ask by Steerpike translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]]

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对象中元素的顺序。)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...