使用grep在select jquery中加载选项

时间:2014-04-25 06:05:32

标签: javascript jquery json

我有以下JSON字符串

var dropDownJSONval = '[
    { "Text": "Apple", "Value": "1" }, 
    { "Text": "Orange", "Value": "2" }, 
    { "Text": "pine", "Value": "3" }, 
    { "Text": "Grape", "Value": "4" }
]'; 

我需要在下拉列表中添加这些JSON对象作为选项。

但是,我不需要在下拉列表中添加Grape。如何在Jquery中使用GREP功能忽略葡萄?

<div>
     <select id="fruits"></select>
</div>

2 个答案:

答案 0 :(得分:0)

尝试,

var fruits = $('#fruits');

$.each(dropDownJSONval ,function(_,val){ 
     if(val.Text==="Grape") { return; }
     fruits.append('<option value='+ val.Value +'>' + val.Text + '</option>');
});

DEMO

答案 1 :(得分:0)

根据OP对@RajaprabhuAravindasamy的评论回答

我想知道GREP的确切含义

修改@RajaprabhuAravindasamy回答使用jQuery.grep()

  

查找满足过滤函数的数组元素。原始数组不受影响。

使用

var fruits = $('#fruits');
 var dropDownJSONval = [{ "Text": "Apple", "Value": "1" }, { "Text": "Orange", "Value": "2" },{ "Text": "pine", "Value": "3" }, { "Text": "Grape", "Value": "4" }]; 

var filtered = jQuery.grep(dropDownJSONval, function(val){
    return val.Text !== "Grape"; 
})

$.each(filtered ,function(_,val){      
     fruits.append('<option value='+ val.Value +'>' + val.Text + '</option>');
});

DEMO

相关问题