简体   繁体   中英

sort javascript populated select list by alphabetical order

I'm trying to sort my javascript popuplated select list and ive searched through all the other posts on this site but i cant get it to work...

here is my javascript that auto populates the select list from an data in an SQL db:

for (clientKey in clientProjectsHash) {
            //alert("client:" + clientKey + ", name: " + clientProjectsHash[clientKey].name);
            clientSelect.options[clientSelect.options.length] = new Option(clientProjectsHash[clientKey].name, clientKey);

            if(selectedClientId == undefined || selectedClientId == 0) {
                if(clientKey > 0) {
                    selectedClientId=clientKey;
                }
            }

ive tried to add: clientProjectsHash.sort(); to the top but it doesn't work... anyone help is appreciated!

this is my other function to get the first client ID from database:

function getInitialClient() {
    for (clientKey in clientProjectsHash) {
        if(clientKey > 0) {
            return clientKey;
        }
    }
}

Try something like this:

var list = [];
for(key in clientProjectsHash)
    list.push(key);
list.sort();
for(var i=0; i<list.length; i++)
{
   clientSelect.options[clientSelect.options.length] = new Option(clientProjectsHash[list[i]].name, clientKey);

        if(selectedClientId == undefined || selectedClientId == 0) {
            if(clientKey > 0) {
                selectedClientId=clientKey;
            }
        }
}

Here we go.

You want to sort an object's enumerable keys by their values.

  • You can use Object.keys to get the enumerable properties of an object.

  • Then, you can use Array.map to convert each key, to its value in the object.

(That link has a shim for older browsers in both of those)

  • Then you can call the normal sort function on them.

Example

Let's say your object is something like

var obj = {
    "a":"Hello",
    "b":"World",
    "c":"AAAA",
    "d":"ZZZZ",    
};

var a = Object.keys(obj).map(function(elem){ // Get the keys, and map them
    return obj[elem];     // to their value
}).sort(); // then sort

Here is a working fiddle

Your case:

In your case, this would be something like

var sortedValues = Object.keys(clientProjectsHash).map(function(elem){ // Get the keys, and map them
        return clientProjectsHash[elem];     // to their value
    }).sort();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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