1

我正在尝试按字母顺序对下拉菜单(哈希)进行排序...我尝试了某人发布的排序方法,但我得到的只是每个下拉菜单名称的“未定义”

这是哈希表:

        var clientProjectsHash = {};
    clientProjectsHash['4'] = {};
    clientProjectsHash['4']['name'] = 'Alterna Savins & Credit Union';
    clientProjectsHash['4']['projects'] = {};
    clientProjectsHash['5'] = {};
    clientProjectsHash['5']['name'] = 'BDC';
    clientProjectsHash['5']['projects'] = {};
    clientProjectsHash['3'] = {};
    clientProjectsHash['3']['name'] = 'BELL';
    clientProjectsHash['3']['projects'] = {};
    clientProjectsHash['6'] = {};
    clientProjectsHash['6']['name'] = 'BNC';
    clientProjectsHash['6']['projects'] = {};

function getSortedKeys(obj) {
    var keys = []; for(var key in obj) keys.push(key);
    return keys.sort(function(a,b){return obj[a]-obj[b]});
}

function populateClientSelect(selectedClientId) {
        //get the client select
        var clientSelect = document.getElementById('clientSelect');

        clientProjectsHash = getSortedKeys(clientProjectsHash);


        //add the clients
        for (clientKey in clientProjectsHash) {

            clientSelect.options[clientSelect.options.length] = new Option(clientProjectsHash[clientKey].name, clientKey);

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

            if (clientKey == selectedClientId)
                clientSelect.options[clientSelect.options.length-1].selected = true;
        }
    }

我尝试的一切都不起作用,这让我发疯!

没有排序功能:下拉菜单抓取最低的键 # 这将是 3,然后在列表上输出“BELL”,我实际上希望“Alterna Savins”显示在下拉列表的顶部..

4

2 回答 2

3

在排序函数中,键数组应该接收键指向的对象,而不是键。您还可以将键的值存储在每个数组对象中以供以后引用。那么排序函数应该是比较每个对象的名称属性:

function getSortedKeys(obj) {
    var keys = []; 
    for(var key in obj) { 
        keys.push(obj[key]);
        keys[keys.length-1]['key'] = key;
    }
    return keys.sort(function(a,b){ return a.name > b.name ? 1 : a.name < b.name ? -1 : 0;});
} // returns [{name:'...', projects:'...', key: '...'}, {}, {}]
于 2013-06-08T21:26:40.537 回答
1

如果你改变clientProjectsHash结构,排序会变得更容易。但是,我不确定你是如何使用clientProjectsHash. 因此,我的建议可能是非现代浏览器中的性能问题。

var clientProjectsHash = [];
clientProjectsHash[0] = {key: 4, name: 'Alterna Savins & Credit Union', projects: {}};
clientProjectsHash[1] = {key: 5, name: 'BDC', projects: {}};
clientProjectsHash[2] = {key: 3, name: 'BELL', projects: {}};
clientProjectsHash[3] = {key: 6, name: 'BNC', projects: {}};

function sorter(a, b) {
  if( a.name < b.name ) return -1;
  if( a.name > b.name ) return 1;
  return 0;
}

clientProjectsHash.sort(sorter);

我假设您将key值保留为对象键以便快速访问。但是,for 循环现在更快了。因此,您可以尝试这样的解决方案并决定走哪条路,而不是采取艰难的方式并受苦。

祝你好运。

于 2013-06-08T21:48:34.347 回答