How to determine if Javascript array contains an object with an attribute that equals a given value?

后端 未结 25 1591
借酒劲吻你
借酒劲吻你 2020-11-22 08:17

I have an array like

vendors = [{
    Name: \'Magenic\',
    ID: \'ABC\'
  },
  {
    Name: \'Microsoft\',
    ID: \'DEF\'
  } // and so on... 
];
         


        
25条回答
  •  孤独总比滥情好
    2020-11-22 09:09

    No loop necessary. Three methods that come to mind:

    Array.prototype.some()

    This is the most exact answer for your question, i.e. "check if something exists", implying a bool result. This will be true if there are any 'Magenic' objects, false otherwise:

    let hasMagenicVendor = vendors.some( vendor => vendor['Name'] === 'Magenic' )
    

    Array.prototype.filter()

    This will return an array of all 'Magenic' objects, even if there is only one (will return a one-element array):

    let magenicVendors = vendors.filter( vendor => vendor['Name'] === 'Magenic' )
    

    If you try to coerce this to a boolean, it will not work, as an empty array (no 'Magenic' objects) is still truthy. So just use magenicVendors.length in your conditional.

    Array.prototype.find()

    This will return the first 'Magenic' object (or undefined if there aren't any):

    let magenicVendor = vendors.find( vendor => vendor['Name'] === 'Magenic' );
    

    This coerces to a boolean okay (any object is truthy, undefined is falsy).


    Note: I'm using vendor["Name"] instead of vendor.Name because of the weird casing of the property names.

    Note 2: No reason to use loose equality (==) instead of strict equality (===) when checking the name.

提交回复
热议问题