使用jQuery过滤JavaScript数组中的项目

13

我有一个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是一个循环遍历数组的函数。问题是我无法按父级过滤它,我尝试使用contains和上面的arrChildOptions2[Parent=opt2],但我无法进行过滤。我希望找到一个简洁的解决方案而不是使用for循环。有什么想法,谢谢。


array.filter() - Blazemonger
3个回答

30

使用jQuery.grep()函数,而不是纠缠于循环,可能会更加成功。

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


非常好,Phil,谢谢你。我之前不知道这个函数,因为我对jQuery还很陌生。但是现在它运行得很好。 - Israfel

3

array.filter() 是原生 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;
  };
}

2

你可以尝试使用jQuery grep, 操作方式如下:

arr = jQuery.grep( JSON_ARRAY, index);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接