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",...]

URIにあるアイテムのみの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
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 に答える
1

ループ内.each()で変更しているため、ループにバグがありposturlContent、2 回目の反復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 に答える