簡體   English   中英

使用jQuery過濾JavaScript Array中的項目

[英]Filter items in JavaScript Array using 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是循環遍歷數組的函數。 問題是我無法通過父進行過濾,我嘗試過使用contains和上面的arrChildOptions2 [Parent = opt2]但是我無法過濾它,我更願意找到一個整潔的解決方案而不是使用一個for循環? 任何想法,歡呼

使用jQuery.grep()函數可能會有更多的運氣,而不是用循環。

此函數“查找滿足過濾函數的數組元素。原始數組不受影響”。

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 grep,像這樣:

arr = jQuery.grep( JSON_ARRAY, index);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM