Reputation: 1322
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;
}
}
}
Upvotes: 1
Views: 1070
Reputation: 276306
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)
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
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();
Upvotes: 2
Reputation: 3760
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;
}
}
}
Upvotes: 2