将唯一的数组项过滤到选择列表中

用户名

我已经在网上进行了一些研究,发现了类似的帖子,但都没有涉及精选列表。我以为我的解决方案可以解决问题,但几次尝试都失败了。我有一个JSON对象存储在本地存储中。数据是:

Contract Id    Contract Number
     4              232-JV-09
     4              232-JV-09
     5              871-PS-03
     7              008-IK-44
     7              008-IK-44
     7              008-IK-44
     9              101-LL-39

我试图在我的选择列表中查看每个合同编号/合同编号之一。我的代码如下(包括失败的尝试);

function PreFetchSurveyContracts() {

    var preFetchSurveyData = JSON.parse(window.localStorage.getItem("preFetchSurveyData"));
    $("#prefetch_contract_numbers").append($('<option value="-1"></option>'));

    var fieldArrayIds = [];
    var fieldArrayNums = [];

    $.each(preFetchSurveyData, function(index,item) {
        if ($.inArray(item.CONTRACT_NUMBER,fieldArrayNums) === -1) {
            fieldArrayIds.push(item.CONTRACT_NUMBER);
            fieldArrayNums.push(item.SURVEY_CONTRACT_ID);
            //fieldArrayIDs[item.SURVEY_CONTRACT_ID] = item.SURVEY_CONTRACT_ID;
            $("#prefetch_contract_numbers").append($('<option value="' + fieldArrayIds[index]/*item.SURVEY_CONTRACT_ID*/+ '">' + fieldArrayNums[index]/*item.CONTRACT_NUMBER*/ + '</option>'));
        }
    });
}

这不起作用,但这是我尝试的最后一次尝试。似乎是按每个字符将它们拆分。而且我什至都不需要两个独立的数组。igh,在这一点上,我有点沮丧。任何有关此主题的帮助将不胜感激。提前致谢。

格雷格·邓肯

看到这个小提琴:http : //jsfiddle.net/b8v9m4yy/

var preFetchSurveyData = [{"ContractID": 4,"ContractNumber": "232-JV-09"},{"ContractID": 4,"ContractNumber": "232-JV-09"},{"ContractID": 5,"ContractNumber": "871-PS-03"},{"ContractID": 7,"ContractNumber": "008-IK-44"},{"ContractID": 7,"ContractNumber": "008-IK-44"},{"ContractID": 7,"ContractNumber": "008-IK-44"},{"ContractID": 9,"ContractNumber": "101-LL-39"}]

// create 2 array variables. 1 to hold the unique objects
// one to hold just the contract ids
var unique = [];
var ids = []
$.each(preFetchSurveyData, function(idx, item){

    // check to see if contract ID already exists in array
    if($.inArray(item.ContractID, ids) === -1){ 

        // if doesn't already exist add the item to the unique array
        // and the ContractID to the ids array
        unique.push(item);
        ids.push(item.ContractID);
    }
});

$("#prefetch_contract_numbers").append($('<option value="-1">- Select -</option>'));

// loop through the unique items and add them to the select
$.each(unique, function(idx, item){
    $("#prefetch_contract_numbers").append($('<option value="' + item.ContractID + '">' + item.ContractNumber + '</option>'));
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章