Filter items in JavaScript Array using jQuery

后端 未结 3 1216
不思量自难忘°
不思量自难忘° 2021-02-05 16:39

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:\'o         


        
相关标签:
3条回答
  • 2021-02-05 17:15

    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;
      };
    }
    
    0 讨论(0)
  • 2021-02-05 17:16

    Yes try jquery grep, like this:

    arr = jQuery.grep( JSON_ARRAY, index);
    
    0 讨论(0)
  • 2021-02-05 17:22

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

    0 讨论(0)
提交回复
热议问题