Jquery how to find an Object by attribute in an Array

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

提交回复
热议问题