我有像
这样的数据userlist=[
{
"label": "veera_ss.com",
"value": "veera_ss.com"
},
{
"label": "v_v.com",
"value": "v_v.com"
},
{
"label": "sample_vh.com",
"value": "sample_vh.com"
},
{
"label": "sample_vh.com",
"value": "sample_vh.com"
},
{
"label": "nabeel.ahameed_vh.com",
"value": "nabeel.ahameed_vh.com"
}
]
我需要遍历此操作并从此列表中删除匹配的元素,例如,如果值为v_v.com,sample_vh.com
将从列表中删除。感谢。
userlist=[
{
"label": "veera_ss.com",
"value": "veera_ss.com"
},
{
"label": "sample_vh.com",
"value": "sample_vh.com"
},
{
"label": "nabeel.ahameed_vh.com",
"value": "nabeel.ahameed_vh.com"
}
]
答案 0 :(得分:4)
您可以在此上下文中使用$.grep()
来实现您想要的效果。
尝试,
var userlist =[{"label":"veera_ss.com","value":"veera_ss.com"},{"label":"v_v.com","value":"v_v.com"},{"label":"sample_vh.com","value":"sample_vh.com"},{"label":"sample_vh.com","value":"sample_vh.com"},{"label":"nabeel.ahameed_vh.com","value":"nabeel.ahameed_vh.com"}]
userlist = $.grep(userlist, function(val){
return val.label !== 'v_v.com' && val.label !== 'sample_vh.com'
}).get(0);
答案 1 :(得分:4)
你不需要jquery。 Javascript数组有一个方法:filter。您可以像使用它一样使用它:
[{"label":"veera_ss.com","value":"veera_ss.com"},
{"label":"v_v.com","value":"v_v.com"},
{"label":"sample_vh.com","value":"sample_vh.com"},
{"label":"sample_vh.com","value":"sample_vh.com"},
{"label":"nabeel.ahameed_vh.com","value":"nabeel.ahameed_vh.com"}]
.filter(function (el) {
return el.label !== 'v_v.com' && el.label !== 'sample_vh.com'
});
答案 2 :(得分:0)
您可以尝试这种方式 -
var arr = []; // will hold final array after removing elements
$.each(userlist,function(v){
if(v.value != "sample_vh.com" && v.value != "sample_vh.com")
arr.push(v);
});
答案 3 :(得分:0)
您可以像这样使用underscorejs reject:
var userlist=[{"label":"veera_ss.com","value":"veera_ss.com"},{"label":"v_v.com","value":"v_v.com"},{"label":"sample_vh.com","value":"sample_vh.com"},{"label":"sample_vh.com","value":"sample_vh.com"},{"label":"nabeel.ahameed_vh.com","value":"nabeel.ahameed_vh.com"}];
userlist = _.reject(userlist, function(user) {
return user.value=="veera_ss.com" || user.value=="v_v.com";
});
答案 4 :(得分:0)
创建一个新列表并进行比较
var userlist=[{"label":"veera_ss.com","value":"veera_ss.com"},
{"label":"v_v.com","value":"v_v.com"},
{"label":"sample_vh.com","value":"sample_vh.com"},
{"label":"sample_vh.com","value":"sample_vh.com"},
{"label":"nabeel.ahameed_vh.com","value":"nabeel.ahameed_vh.com"}]
var newList = []
userlist.forEach(function(item, key) {
if(!newList.some(function(x){
return JSON.stringify(x) === JSON.stringify(item) }))
{
newList.push(item);
}
})
//newList is filtered result.