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

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

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

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

当前回答

将它们移动到一个数组中,对该数组进行排序,然后将该数组用于您的目的。这里有一个解决方案:

let maxSpeed = {
    car: 300, 
    bike: 60, 
    motorbike: 200, 
    airplane: 1000,
    helicopter: 400, 
    rocket: 8 * 60 * 60
};
let 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对象中元素的顺序。

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

在ES8中,你可以使用object .entries()将对象转换为数组:

const maxSpeed = { 车:300, 自行车:60岁 摩托车:200, 飞机:1000, 直升机:400, 火箭:8 * 60 * 60 }; const sortable = Object.entries(maxSpeed) .sort([,a],[,b]) => a-b) .reduce((r, [k, v]) =>({…R, [k]: v}), {}); console.log(合适的);


在ES10中,你可以使用object. fromentries()将数组转换为对象。然后代码可以简化为:

const maxSpeed = { 车:300, 自行车:60岁 摩托车:200, 飞机:1000, 直升机:400, 火箭:8 * 60 * 60 }; const sortable = Object.fromEntries( Object.entries(maxSpeed).sort(([,a],[,b]) => a-b) ); console.log(合适的);

其他回答

另一种解决方法:-

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

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}

非常简短简单!

var sortedList = {};
Object.keys(list).sort((a,b) => list[a]-list[b]).forEach((key) => {
    sortedList[key] = list[key]; });
let toSort = {a:2323, b: 14, c: 799} 
let sorted = Object.entries(toSort ).sort((a,b)=> a[1]-b[1]) 

输出:

[ [ "b", 14 ], [ "c", 799 ], [ "a", 2323 ] ]

下划线。js或Lodash.js用于高级数组或对象排序

var data = { "models": { "LTI": [ "TX" ], "Carado": [ "A", "T", "A(пасс)", "A(груз)", "T(пасс)", "T(груз)", "A", "T" ], "SPARK": [ "SP110C 2", "sp150r 18" ], "Autobianchi": [ "A112" ] } }; var arr = [], obj = {}; for (var i in data.models) { arr.push([i, _.sortBy(data.models[i], function(el) { return el; })]); } arr = _.sortBy(arr, function(el) { return el[0]; }); _.map(arr, function(el) { return obj[el[0]] = el[1]; }); console.log(obj); <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js" integrity="sha256-qXBd/EfAdjOA2FGrGAG+b3YBn2tn5A6bhz+LSgYD96k=" crossorigin="anonymous"></script>