使用jQuery过滤JavaScript Array中的项目

时间:2010-01-18 09:34:50

标签: 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:'Parent 2 - Child 2'}
    ];

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

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

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

3 个答案:

答案 0 :(得分:30)

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

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

答案 1 :(得分:2)

是的尝试jquery grep,像这样:

arr = jQuery.grep( JSON_ARRAY, index);

答案 2 :(得分:2)

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