Jquery how to find an Object by attribute in an Array

前端 未结 11 2174
灰色年华
灰色年华 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:43

    The error was that you cannot use this in the grep, but you must use a reference to the element. This works:

    function findPurpose(purposeName){
        return $.grep(purposeObjects, function(n, i){
          return n.purpose == purposeName;
        });
    };
    
    findPurpose("daily");
    

    returns:

    [Object { purpose="daily"}]
    

提交回复
热议问题