使用jQuery过滤JavaScript数组中的项
我有一个JavaScript数组,如下所示,我需要对其进行过滤,以便从下面的测试数据中获得正确的子值使用jQuery过滤JavaScript数组中的项,javascript,jquery,Javascript,Jquery,我有一个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:'Pare
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是一个在数组中循环的函数。问题是我不能让它按父级过滤,我尝试过使用contains和上面的arrChildOptions2[parent=opt2]但我不能让它过滤,我更愿意找到一个简洁的解决方案,而不是使用for循环?任何想法,干杯您可能会更幸运地使用该函数,而不是在循环中胡闹
此函数“查找满足筛选函数的数组元素。原始数组不受影响”。是尝试jquery grep,如下所示:
arr = jQuery.grep( JSON_ARRAY, index);
存在于普通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;
};
}
if(!Array.prototype.filter)
{
Array.prototype.filter=函数(fun/*,thisArg*/)
{
“严格使用”;
if(this==void 0 | | this==null)
抛出新的TypeError();
var t=对象(本);
var len=t.length>>>0;
如果(乐趣的类型!=“功能”)
抛出新的TypeError();
var-res=[];
var thisArg=arguments.length>=2?参数[1]:无效0;
对于(变量i=0;i
非常好,菲尔,谢谢你,我不知道这个函数,对jquery来说还是很新的,非常有用。