Javascript基于值对键值对象进行排序

时间:2013-01-08 05:20:17

标签: javascript jquery

我有一个像下面这样的对象。尝试根据值按升序重新排列。与Javascript数组排序方法类似。

    var masterList = {
    "1": "google",
    "2": "yahoo",
    "3": "msn",
    "4": "stackoverflow",
    "5": "github",
    "6": "jsfiddle",
    "7": "amazon",
    "8": "ebay"
}

请让我知道更好的解决方案...

3 个答案:

答案 0 :(得分:51)

JavaScript对象没有订单。即使大多数浏览器按照相同的顺序迭代创建属性,也无法保证,因此对象不支持排序。

有关详细信息,请参阅此处:Does JavaScript Guarantee Object Property Order?

您可能也对此问题的John Resig has got to say感兴趣。


如果您需要可排序列表,则必须将其存储为对象数组:

var masterList = [
    { key: 1, val: "google" },
    { key: 2, val: "yahoo" },
    { key: 3, val: "msn" },
    { key: 4, val: "stackoverflow" },
    { key: 5, val: "github" },
    { key: 6, val: "jsfiddle" },
    { key: 7, val: "amazon" },
    { key: 8, val: "ebay" }
];

然后,要对它们进行排序,只需使用常规数组的sort方法:

masterList = masterList.sort(function (a, b) {
    return a.val.localeCompare( b.val );
});

这是小提琴:http://jsfiddle.net/ASrUD/

答案 1 :(得分:6)

var obj = {
    "1": "google",
    "2": "yahoo",
    "3": "msn",
    "4": "stackoverflow",
    "5": "github",
    "6": "jsfiddle",
    "7": "amazon",
    "8": "ebay"
};

var arr = [];

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        arr.push(obj[key]);
    }
}

alert(arr.sort());

这将按升序对您的值进行排序。让我给一些时候会回复你如何将其转换为对象。

答案 2 :(得分:0)

var masterList = {
    "2": "yahoo",
    "3": "msn",
    "4": "stackoverflow",
    "5": "github",
    "6": "jsfiddle",
    "7": "amazon",
    "8": "ebay",
    "1": "google",
   }
var masterList_ = {}

Object.keys(masterList).sort().forEach(a=>masterList_[a]=masterList[a])
console.log(masterList_)