使用grep加载select jquery中的选项

load options in select jquery using grep

本文关键字:选项 jquery select grep 加载 使用      更新时间:2023-09-26

我有以下JSON字符串

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

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

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

机身

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

根据@RajaparbhuAravindasamy回答的OP评论

我想知道GREP的确切含义

修改@RajaparbhuAravindasamy的答案以使用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

Try,

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

演示