2013-04-24 120 views
0

我有一個JSON對象陣列陣列減去從JSON對象的JavaScript

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

從你的'posturlContent'對象中刪除最後一個逗號(最後一個括號後)。 – SimonDever 2013-04-24 03:55:35

回答

2

我最好使用逆邏輯,循環posturlContent$.grep,以及檢查與urisindexOf

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

http://jsfiddle.net/ExBsa/

注:支持陣列.index在IE < = 8中,使用mdn polyfill,或簡單的jQuery的$ .inArray由vher2建議。

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

2

你可以試試這個:

var tmp = []; 
$.each(posturlContent, function(){ 
    if ($.inArray(this.Uri, uris) !== -1) { 
     tmp.push(this); 
    } 
}); 
posturlContent = tmp; 
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]; 
     } 
    });