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

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

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

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

当前回答

我为此做了一个插件,它接受1个arg,这是一个未排序的对象,并返回一个对象,已排序的道具值。这将适用于所有二维对象,如{"Nick": 28, "Bob": 52}…

var sloppyObj = {
    'C': 78,
    'A': 3,
    'B': 4
};

// Extend object to support sort method
function sortObj(obj) {
    "use strict";

    function Obj2Array(obj) {
        var newObj = [];
        for (var key in obj) {
            if (!obj.hasOwnProperty(key)) return;
            var value = [key, obj[key]];
            newObj.push(value);
        }
        return newObj;
    }

    var sortedArray = Obj2Array(obj).sort(function(a, b) {
        if (a[1] < b[1]) return -1;
        if (a[1] > b[1]) return 1;
        return 0;
    });

    function recreateSortedObject(targ) {
        var sortedObj = {};
        for (var i = 0; i < targ.length; i++) {
            sortedObj[targ[i][0]] = targ[i][1];
        }
        return sortedObj;
    }
    return recreateSortedObject(sortedArray);
}

var sortedObj = sortObj(sloppyObj);

alert(JSON.stringify(sortedObj));

下面是该函数按预期工作的演示 http://codepen.io/nicholasabrams/pen/RWRqve?editors=001

其他回答

谢谢你,继续回答@Nosredna

现在我们知道对象需要转换为数组,然后对数组排序。这对于按字符串排序数组(或转换对象为数组)非常有用:

Object {6: Object, 7: Object, 8: Object, 9: Object, 10: Object, 11: Object, 12: Object}
   6: Object
   id: "6"
   name: "PhD"
   obe_service_type_id: "2"
   __proto__: Object
   7: Object
   id: "7"
   name: "BVC (BPTC)"
   obe_service_type_id: "2"
   __proto__: Object


    //Sort options
    var sortable = [];
    for (var vehicle in options)
    sortable.push([vehicle, options[vehicle]]);
    sortable.sort(function(a, b) {
        return a[1].name < b[1].name ? -1 : 1;
    });


    //sortable => prints  
[Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2]]
    0: Array[2]
    0: "11"
    1: Object
        id: "11"
        name: "AS/A2"
        obe_service_type_id: "2"
        __proto__: Object
        length: 2
        __proto__: Array[0]
    1: Array[2]
    0: "7"
    1: Object
        id: "7"
        name: "BVC (BPTC)"
        obe_service_type_id: "2"
        __proto__: Object
        length: 2
var list = {
    "you": 100, 
    "me": 75, 
    "foo": 116, 
    "bar": 15
};

function sortAssocObject(list) {
    var sortable = [];
    for (var key in list) {
        sortable.push([key, list[key]]);
    }
    // [["you",100],["me",75],["foo",116],["bar",15]]

    sortable.sort(function(a, b) {
        return (a[1] < b[1] ? -1 : (a[1] > b[1] ? 1 : 0));
    });
    // [["bar",15],["me",75],["you",100],["foo",116]]

    var orderedList = {};
    for (var idx in sortable) {
        orderedList[sortable[idx][0]] = sortable[idx][1];
    }

    return orderedList;
}

sortAssocObject(list);

// {bar: 15, me: 75, you: 100, foo: 116}

找出每个元素的频率,并按频率/值进行排序。

Let response =["苹果","橘子","苹果","香蕉","橘子","香蕉","香蕉"]; 设frequency = {}; response.forEach(函数(项){ 频率[项目]=频率[项目]?频率[项]+ 1:1; }); console.log(频率); let intents = Object.entries(frequency) .sort((a, b) => b[1] - a[1]) . map(函数(x) { 返回x [0]; }); console.log(意图);

输出:

{ apple: 2, orange: 2, banana: 3 }
[ 'banana', 'apple', 'orange' ]

另一种解决方法:-

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

@marcusR回答的“箭头”版本供参考

var myObj = { you: 100, me: 75, foo: 116, bar: 15 };
keysSorted = Object.keys(myObj).sort((a, b) => myObj[a] - myObj[b]);
alert(keysSorted); // bar,me,you,foo

更新:2017年4月 返回一个上面定义的排序后的myObj对象。 const myObj ={你:100,我:75,foo: 116, bar: 15}; Const result = 种(myObj) .sort((a, b) => myObj[a] - myObj[b]) .reduce ( (_sortedObj, key) => ({ ……_sortedObj, (例子):myObj(例子) }), {} ); document . write (JSON.stringify(结果));

更新:2021年3月-对象。带有排序功能的条目(根据注释更新) const myObj ={你:100,我:75,foo: 116, bar: 15}; const result =对象 .entries (myObj) .sort((a, b) => a[1] - b[1]) .reduce((_sortedObj, [k,v]) => ({ ……_sortedObj, [k]: v }, {}) document . write (JSON.stringify(结果));