0

我有一个 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",...]

我只需要在 uris 中的项目的 posturlContent 的输出,因此如下所示。

   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();
        });
    })
4

4 回答 4

2

我会使用逆逻辑,循环posturlContent,并$.grep检查:urisindexOf

posturlContent = $.grep(posturlContent, function(item){
    return uris.indexOf(item.Uri) > -1;
});

http://jsfiddle.net/ExBsa/

注意:要在 IE <= 8 中支持 Array.indexOf,请使用mdn polyfill,或者按照 vher2 的建议简单地使用 jQuery 的 $.inArray。

于 2013-04-24T04:00:56.750 回答
2

你可以试试这个:

var tmp = [];
$.each(posturlContent, function(){
    if ($.inArray(this.Uri, uris) !== -1) {
        tmp.push(this);
    }
});
posturlContent = tmp;
于 2013-04-24T04:02:36.507 回答
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();
    }));
})

演示:小提琴

于 2013-04-24T03:55:16.970 回答
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];
        }
    });
于 2015-11-27T08:00:38.730 回答