gpt4 book ai didi

javascript - 按名称而不是键对我的 javascript 下拉菜单进行排序#

转载 作者:行者123 更新时间:2023-11-30 10:30:58 25 4
gpt4 key购买 nike

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

这是哈希表:

        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”显示在下拉列表的顶部。

最佳答案

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

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: '...'}, {}, {}]

关于javascript - 按名称而不是键对我的 javascript 下拉菜单进行排序#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17003844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com