我有一个Json对象数组
posturlContent = [
{ "Title": "Bbc news live", "Content": "<div>this is a test BBC </div>", "Uri": "http://bbc.co.uk" },
{ "Title": "CNN news live", "Content": "<div>this is a test CNN</div>", "Uri": "http://cnn.com" },
{ "Title": "Youtube news live", "Content": "<div>this is a test Youtube </div>", "Uri": "http://youtube.com" },
];
我有一个JS数组
uris =["http://cnn.com", "http://abcnews.com",...]
我只需要输出posturlContent,而不仅仅是uris中的项目。
posturlContent = [
{ "Title": "CNN news live", "Content": "<div>this is a test CNN</div>", "Uri": "http://cnn.com" }
];
我尝试使用此功能但返回空的posturlContent
$.each(uris, function(){
var siteUrl = this.valueOf();
posturlContent = $.grep(posturlContent, function(item){
return item.Uri.toLowerCase() != siteUrl.toLowerCase();
});
})
答案 0 :(得分:2)
我使用逆逻辑,使用posturlContent
循环$.grep
,并使用uris
检查indexOf
:
posturlContent = $.grep(posturlContent, function(item){
return uris.indexOf(item.Uri) > -1;
});
注意:要支持IE&lt; = 8中的Array.indexOf,请使用mdn polyfill,或者只使用vher2建议的jQuery的$ .inArray。
答案 1 :(得分:2)
你可以试试这个:
var tmp = [];
$.each(posturlContent, function(){
if ($.inArray(this.Uri, uris) !== -1) {
tmp.push(this);
}
});
posturlContent = tmp;
答案 2 :(得分:1)
你的.each()
循环是错误的,因为你在循环中修改posturlContent
,在第二次迭代中posturlContent
将是空的。
var original = posturlContent;
posturlContent = [];
$.each(uris, function(i, siteUrl) {
posturlContent = posturlContent.concat($.grep(original, function(item) {
return item.Uri.toLowerCase() == siteUrl.toLowerCase();
}));
})
演示:Fiddle
答案 3 :(得分:1)
var posturlContent = [
{"Title": "Bbc news live", "Content": "<div>this is a test BBC </div>", "Uri": "http://bbc.co.uk" },
{ "Title": "CNN news live", "Content": "<div>this is a test CNN</div>", "Uri": "http://cnn.com" },
{ "Title": "Youtube news live", "Content": "<div>this is a test Youtube </div>", "Uri": "http://youtube.com" },
];
var uris = ["http://cnn.com", "http://abcnews.com"]
var outputArr = posturlContent.filter(function(data){
for(var i=0; i<uris.length; i++) {
return data.Uri == uris[i];
}
});