Javascript 根据值对键值对对象进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14208651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:01:57  来源:igfitidea点击:

Javascript Sort key value pair object based on value

javascriptjquery

提问by r1webs

I have an object like below. Trying to rearrange it in ascending order based on value. Similar to Javascript array sort method.

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

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

Please let me know the better solution...

请告诉我更好的解决方案...

回答by Joseph Silber

JavaScript objects have no order. Even though most browsers do iterate in the same order the properties were created, there's no guarantee, so sorting is not supported on objects.

JavaScript 对象没有顺序。尽管大多数浏览器确实以创建属性的相同顺序进行迭代,但不能保证,因此对象不支持排序。

See here for more info: Does JavaScript Guarantee Object Property Order?

有关更多信息,请参见此处:JavaScript 是否保证对象属性顺序?

You might also be interested in what John Resig has got to sayon the matter.

您可能还对John Resig对此事的看法感兴趣。



If you need a sort-able list, you'll have to store it as an array of objects:

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

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" }
];

Then, to sort them, just use the regular array's sortmethod:

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

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

Here's the fiddle: http://jsfiddle.net/ASrUD/

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

回答by satheeaseelan

    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());

This will sort your values in ascending order. let me give sometime will revert you with how to convert that to an object.

这将按升序对您的值进行排序。让我给一些时间来告诉您如何将其转换为对象。