使用jQuery过滤JavaScript Array中的项目

我有一个JavaScript数组,我需要过滤以从下面的测试数据中获取正确的子值。

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循环? 任何想法,欢呼

使用jQuery.grep()函数可能会有更多的运气,而不是乱用循环。

此函数“查找满足过滤函数的数组元素。原始数组不受影响”。

是的尝试jquery grep,像这样:

 arr = jQuery.grep( JSON_ARRAY, index); 

array.filter()存在于vanilla JavaScript中:

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

该文档页面包含旧版浏览器的polyfill:

 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; }; } 

您可以利用jQuery.filter()函数从匹配元素的子集构造新的jQuery对象。

 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($("").val(this.Value).text(this.Text)); });