使用jQuery过滤JavaScript Array中的项目 [英] Filter items in JavaScript Array using jQuery

查看:64
本文介绍了使用jQuery过滤JavaScript Array中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a JavaScript array as below which I need to filter to get the correct child values from the test data below.

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

这些值用于根据父下拉列表的更改事件填充下拉列表,如下所示。 / p>

The values are used to populate a dropdown based on the change event of a parent dropdown as below.

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

其中additems是循环遍历数组的函数。问题是我无法通过父级过滤,我尝试使用包含和上面的 arrChildOptions2 [Parent = opt2] ,但我无法将其转换为过滤器,我更愿意找到一个整洁的解决方案,而不是使用for循环?任何想法,欢呼

where additems is a function that loops through the array. Problem is I can't get it to filter by parent, I've tried using contains and the above arrChildOptions2[Parent=opt2] but I can't get it to filter, I'd prefer to find a neat solution rather than use a for loop? Any ideas, cheers

推荐答案

使用 jQuery.grep()函数而不是乱用循环。

You might have more luck using the jQuery.grep() function rather than messing around with loops.

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

This function "Finds the elements of an array which satisfy a filter function. The original array is not affected".

这篇关于使用jQuery过滤JavaScript Array中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆