开发者

Filter items in JavaScript Array using jQuery

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

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

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


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".


array.filter() exists in vanilla JavaScript:

function isBigEnough(element) {
  return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

That documentation page includes a polyfill for older browsers:

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


Yes try jquery grep, like this:

arr = jQuery.grep( JSON_ARRAY, index);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜