简体   繁体   English

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

[英]Javascript Sort key value pair object based on value

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...请告诉我更好的解决方案...

JavaScript objects have no order. JavaScript 对象没有顺序。 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.尽管大多数浏览器确实以创建属性的相同顺序进行迭代,但不能保证,因此对象不支持排序。

See here for more info: Does JavaScript Guarantee Object Property Order?有关更多信息,请参见此处: JavaScript 是否保证对象属性顺序?

You might also be interested in what John Resig has got to say on 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 sort method:然后,要对它们进行排序,只需使用常规数组的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/

 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.让我给一些时间来告诉您如何将其转换为对象。

 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_)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM