Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

jquery - 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.

    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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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


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:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...