Jquery how to find an Object by attribute in an Array

前端 未结 11 2159
灰色年华
灰色年华 2020-12-02 11:55

Given I have an array of \"purpose\" objects:

//array of purpose objects:
var purposeObjects = [
    {purpose: \"daily\"},
    {purpose: \"weekly\"},
    {pu         


        
11条回答
  •  猫巷女王i
    2020-12-02 12:39

    copied from polyfill Array.prototype.find code of Array.find, and added the array as first parameter.

    you can pass the search term as predicate function

    // Example
    var listOfObjects = [{key: "1", value: "one"}, {key: "2", value: "two"}]
    var result = findInArray(listOfObjects, function(element) {
      return element.key == "1";
    });
    console.log(result);
    
    // the function you want
    function findInArray(listOfObjects, predicate) {
          if (listOfObjects == null) {
            throw new TypeError('listOfObjects is null or not defined');
          }
    
          var o = Object(listOfObjects);
    
          var len = o.length >>> 0;
    
          if (typeof predicate !== 'function') {
            throw new TypeError('predicate must be a function');
          }
    
          var thisArg = arguments[1];
    
          var k = 0;
    
          while (k < len) {
            var kValue = o[k];
            if (predicate.call(thisArg, kValue, k, o)) {
              return kValue;
            }
            k++;
          }
    
          return undefined;
    }

提交回复
热议问题