简体   繁体   English

如何对该JavaScript对象进行排序?

[英]How do I sort this javascript object?

If I have a javascript object like this: 如果我有这样的JavaScript对象:

{ 'apples':14, 'oranges': 1, 'bananas':4 }

How can I sort it to an Array, descending order, based on the value? 如何根据值将其排序为降序排列的数组?

Result: 结果:

[ 'apples', 'bananas', 'oranges' ]

Because 14, 4, 1 ...descending order 因为14、4、1 ...降序

Pull all the keys from the object into an array and sort the array. 将所有键从对象中拉到数组中并对数组进行排序。

var o = { 'apples':14, 'oranges': 1, 'bananas':4 };
var a = [];

for (var key in o) {
    a.push(key);
}
a.sort();

If you think you need to protect against properties that have been added to the Object prototype in an unfriendly way (or don't know), then you should do it like this: 如果您认为需要防止以不友好的方式(或不知道)添加到对象原型的属性,那么您应该这样做:

var o = { 'apples':14, 'oranges': 1, 'bananas':4 };
var a = [];

for (var key in o) {
    if (o.hasOwnProperty(key)) {
        a.push(key);
    }
}
a.sort();

EDIT: now that the original question has been changed and the requirement is now that the keys are sorted in order by the value in the original object, that would have to be done differently: 编辑:现在,原始问题已更改,并且要求现在是按原始对象中的值按顺序对键进行排序,这将必须以其他方式完成:

var o = { 'apples':14, 'oranges': 1, 'bananas':4 };
var a = [];

for (var key in o) {
    if (o.hasOwnProperty(key)) {
        a.push(key);
    }
}
a.sort(function(x, y) {return(o.y - o.x);});

here is my approach to this problem: 这是我解决这个问题的方法:

var o={ 'apples':14, 'oranges': 1, 'bananas':4 };
var a=[];
for(var fruit in o)
{
   if(o[fruit])
      a[fruit]=o[fruit];  i.e // a[apples]=14;
}

a.sort(function(a,b){return Number(a)-Number(b);});

now a is sorted by the value. 现在,a按值排序。

console.log("Sorted Fruits:")
for(var fruit in o)
{
    if(o[fruit])
       console.log(fruit);
}

Here is the ES5 way to do it: 这是ES5的实现方法:

var fruit = { 'apples':14, 'oranges':1, 'grapefruit':70, 'bananas':4 }

var orderedByDescendingQuantities = Object.keys(fruit).sort(function (x, y) {
    return fruit[y] - fruit[x];
});

alert(orderedByDescendingQuantities);

See http://jsfiddle.net/gh5x8/ 看到http://jsfiddle.net/gh5x8/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM