如果我有一个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(合适的);

其他回答

另一个关于Object的例子。值、sort()和展开运算符。

var paintings = {
    0: {
        title: 'Oh my!',
        year: '2020',
        price: '3000'
    },
    1: {
        title: 'Portrait V',
        year: '2021',
        price: '2000'
    },
    2: {
        title: 'The last leaf',
        year: '2005',
        price: '600'
    }
}

我们使用object .values将对象转换为对象数组:

var toArray = Object.values(paintings)

然后我们对数组进行排序(按年份和价格),使用spread操作符使原始数组不可变,并使用sort()方法对数组进行排序:

var sortedByYear = [...toArray].sort((a, b) => a.year - b.year)
var sortedByPrice = [...toArray].sort((a, b) => a.price - b.price)

最后,我们生成新的排序对象(同样,使用展开运算符来保持以[x: number]为键的对象的object的原始形式):

var paintingsSortedByYear = {
    ...sortedByYear
}

var paintingsSortedByPrice = {
    ...sortedByPrice
}

希望这对你有所帮助!

找不到上面的答案,既工作又小,并支持嵌套对象(不是数组),所以我写了自己的一个:)工作与字符串和整数。

  function sortObjectProperties(obj, sortValue){
      var keysSorted = Object.keys(obj).sort(function(a,b){return obj[a][sortValue]-obj[b][sortValue]});
      var objSorted = {};
      for(var i = 0; i < keysSorted.length; i++){
          objSorted[keysSorted[i]] = obj[keysSorted[i]];
      }
      return objSorted;
    }

用法:

    /* sample object with unsorder properties, that we want to sort by 
    their "customValue" property */

    var objUnsorted = {
       prop1 : {
          customValue : 'ZZ'
       },
       prop2 : {
          customValue : 'AA'
       }
    }

    // call the function, passing object and property with it should be sorted out
    var objSorted = sortObjectProperties(objUnsorted, 'customValue');

    // now console.log(objSorted) will return:
    { 
       prop2 : {
          customValue : 'AA'
       },
       prop1 : {
          customValue : 'ZZ'
       } 
    }

我们不想复制整个数据结构,也不想在需要关联数组的地方使用数组。

这里有另一种方法来做与bonna相同的事情:

var列表={“我”“你”:100:75年,“foo”:116年,“酒吧”:15}; keysSorted = Object.keys(list).sort(function(a,b){返回list[a]-list[b]}) console.log (keysSorted);/ /酒吧,我,你,foo

@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(结果));

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}