Jquery how to find an Object by attribute in an Array

前端 未结 11 2029
灰色年华
灰色年华 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条回答
  • 2020-12-02 12:22

    Use the Underscore.js findWhere function (http://underscorejs.org/#findWhere):

    var purposeObjects = [
        {purpose: "daily"},
        {purpose: "weekly"},
        {purpose: "monthly"}
    ];
    
    var daily = _.findWhere(purposeObjects, {purpose: 'daily'});
    

    daily would equal:

    {"purpose":"daily"}
    

    Here's a fiddle: http://jsfiddle.net/spencerw/oqbgc21x/

    To return more than one (if you had more in your array) you could use _.where(...)

    0 讨论(0)
  • 2020-12-02 12:23

    No need for jQuery.

    JavaScript arrays have a find method, so you can achieve that in one line:

    array.find((o) => { return o[propertyName] === propertyValue }
    

    Example

    
    const purposeObjects = [
        {purpose: "daily"},
        {purpose: "weekly"},
        {purpose: "monthly"}
    ];
    
    purposeObjects.find((o) => { return o["purpose"] === "weekly" }
    
    // output -> {purpose: "weekly"}
    

    If you need IE compatibility, import this polyfill in your code.

    0 讨论(0)
  • 2020-12-02 12:25

    you should pass reference on item in grep function:

    function findPurpose(purposeName){
        return $.grep(purposeObjects, function(item){
          return item.purpose == purposeName;
        });
    };
    

    Example

    0 讨论(0)
  • 2020-12-02 12:26

    If your array is actually a set of JQuery objects, what about simply using the .filter() method ?

    purposeObjects.filter('[purpose="daily"]')
    
    0 讨论(0)
  • 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;
    }

    0 讨论(0)
  • 2020-12-02 12:41

    Javascript has a function just for that: Array.prototype.find. As example

    function isBigEnough(element) {
      return element >= 15;
    }
    
    [12, 5, 8, 130, 44].find(isBigEnough); // 130
    

    It not difficult to extends the callback to a function. However this is not compatible with IE (and partially with Edge). For a full list look at the Browser Compatibility

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