2010-01-18 33 views
13

我有一個JavaScript數組,如下所示,我需要從下面的測試數據中篩選出正確的子數值。在JavaScript中過濾項目使用jQuery的數組

var arrChildOptions2 = [ 
     {Parent:'opt1',Value:'opt1',Text:'Parent1 - Child 1'}, 
     {Parent:'opt2',Value:'opt1',Text:'Parent 2 - Child 1'}, 
     {Parent:'opt2',Value:'opt2',Text:'Parent 2 - Child 2'} 
    ]; 

這些值用於基於父級下拉列表的更改事件填充下拉列表,如下所示。

$(function() { 
    $('#ddl1').change(function() { 
     $('#ddl2 option:gt(0)').remove(); 
     $('#ddl2').addItems('#ddl2', arrChildOptions2[Parent=opt2]); 
    }); 
}); 

其中additems是一個循環遍歷數組的函數。問題是我不能讓它過濾父,我已經嘗試使用包含和以上arrChildOptions2 [Parent = opt2]但我不能讓它過濾,我寧願找到一個整潔解決方案而不是使用for循環?任何想法,歡呼

+0

['array.filter()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) – Blazemonger

回答

30

使用jQuery.grep()函數,你可能會有更多的運氣,而不是亂搞循環。

該函數「查找滿足過濾函數的數組元素,原始數組不受影響」。

+0

優秀菲爾,謝謝,我沒有意識到這個功能,對於jquery來說還是很新鮮的東西,很有用。 – Israfel

2

是嘗試jQuery的grep的,就像這樣:

arr = jQuery.grep(JSON_ARRAY, index); 
2

array.filter()存在於香草的JavaScript:

function isBigEnough(element) { 
    return element >= 10; 
} 
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); 
// filtered is [12, 130, 44] 

該文檔頁面包括舊的瀏覽器一個填充工具:

if (!Array.prototype.filter) 
{ 
    Array.prototype.filter = function(fun /*, thisArg */) 
    { 
    "use strict"; 

    if (this === void 0 || this === null) 
     throw new TypeError(); 

    var t = Object(this); 
    var len = t.length >>> 0; 
    if (typeof fun !== "function") 
     throw new TypeError(); 

    var res = []; 
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0; 
    for (var i = 0; i < len; i++) 
    { 
     if (i in t) 
     { 
     var val = t[i]; 

     // NOTE: Technically this should Object.defineProperty at 
     //  the next index, as push can be affected by 
     //  properties on Object.prototype and Array.prototype. 
     //  But that method's new, and collisions should be 
     //  rare, so use the more-compatible alternative. 
     if (fun.call(thisArg, val, i, t)) 
      res.push(val); 
     } 
    } 

    return res; 
    }; 
} 
0

你可以利用jQuery.filter()函數來構造一個新的jQuery ob從匹配元素的子集中剔除。

var result = [ 
 
     {Parent:'opt1',Value:'opt1',Text:'Parent1 - Child 1'}, 
 
     {Parent:'opt2',Value:'opt1',Text:'Parent 2 - Child 1'}, 
 
     {Parent:'opt2',Value:'opt2',Text:'Parent 2 - Child 2'} 
 
    ]; 
 
    
 
     
 
var filteredResult = $(result).filter(function(idx) { 
 
    return result[idx].Parent === 'opt2'; 
 
});   
 
    
 
    
 
var options = $("#result-list"); 
 
$.each(filteredResult, function() { 
 
    options.append($("<option />").val(this.Value).text(this.Text)); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<select id="result-list" name="select" title="List"/>