我有一个jquery数组。在这里我想删除WORLD NEWS项目。 我的阵列是这样的,
[Object { NewsType="WORLD NEWS", NoOfHours=2},
Object { NewsType="LOCAL NEWS", NoOfHours=1},
Object { NewsType="SPORTS NEWS", NoOfHours=2}]
我试过这样,
var remItem ="WORLD" ;
NewsArray.splice($.inArray(remItem, NewsArray), 1);
但是在这里我用硬编码的新闻,它并不好,因为有时它会以一个世界或全球或任何其他类似的名字出现。
我如何解决这个问题?
答案 0 :(得分:1)
你的jSON结构不应该包含=而是它应该在key:value对中。你可以使用grep fun来过滤它
var data= [ { NewsType:"WORLD NEWS", NoOfHours:2}, { NewsType:"LOCAL NEWS", NoOfHours:1}, { NewsType:"SPORTS NEWS", NoOfHours:2} ] var target = "WORLD NEWS"; data = jQuery.grep(data, function(e){ return e.NewsType != target; });
答案 1 :(得分:0)
尝试替换
NewsArray.splice($.inArray(remItem, NewsArray), 1);
与
NewsArray = NewsArray.filter(function(val){return val.NewsType.indexOf(remItem)== -1});
这将过滤掉其中包含WORLD
的项目。
答案 2 :(得分:0)
var y = ['WORLD NEWS','LOCAL NEWS', 'SPORTS NEWS']
var removeItem = 'WORLD NEWS';
y = jQuery.grep(y, function(value) {
return value != removeItem;
});
答案 3 :(得分:0)
尝试使用过滤器
var obj = [{ NewsType:"WORLD NEWS", NoOfHours:2},{ NewsType:"LOCAL NEWS", NoOfHours:1},{ NewsType:"SPORTS NEWS", NoOfHours:2}];
var rez = obj.filter(function(v){
return v.NewsType != "WORLD NEWS";
});
答案 4 :(得分:0)
您可以使用Array.prototype.indexOf()
,$.grep()
arr.splice(arr.indexOf($.grep(arr, function(obj) {
return obj.NewsType === "WORLD NEWS"
})[0]), 1);
var arr = [{
NewsType: "WORLD NEWS",
NoOfHours: 2
}, {
NewsType: "LOCAL NEWS",
NoOfHours: 1
}, {
NewsType: "SPORTS NEWS",
NoOfHours: 2
}];
arr.splice(arr.indexOf($.grep(arr, function(obj) {
return obj.NewsType === "WORLD NEWS"
})[0]), 1);
console.log(JSON.stringify(arr, null, 2))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>