Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an array like

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

How do I check this array to see if "Magenic" exists? I don't want to loop, unless I have to. I'm working with potentially a couple thousand records.

like image 869
David Lozzi Avatar asked Nov 21 '11 19:11

David Lozzi


People also ask

How do you determine if JavaScript array contains an object with an attribute?

Using includes() Method: If array contains an object/element can be determined by using includes() method. This method returns true if the array contains the object/element else return false. Example: html.

How do you check if an array of objects contains a value?

Checking if Array of Objects Includes Object We can use the some() method to search by object's contents. The some() method takes one argument accepts a callback, which is executed once for each value in the array until it finds an element which meets the condition set by the callback function, and returns true .

How do you check if an array has an object JavaScript?

isArray() method is used to check if an object is an array. The Array. isArray() method returns true if an object is an array, otherwise returns false . Note: For an array, the typeof operator returns an object.


1 Answers

No need to reinvent the wheel loop, at least not explicitly (using arrow functions, modern browsers only):

if (vendors.filter(e => e.Name === 'Magenic').length > 0) {   /* vendors contains the element we're looking for */ } 

or, better yet, as it allows the browser to stop as soon as one element is found that matches, so it's going to be faster:

if (vendors.some(e => e.Name === 'Magenic')) {   /* vendors contains the element we're looking for */ } 

EDIT: If you need compatibility with lousy browsers then your best bet is:

if (vendors.filter(function(e) { return e.Name === 'Magenic'; }).length > 0) {   /* vendors contains the element we're looking for */ } 
like image 146
CAFxX Avatar answered Oct 18 '22 12:10

CAFxX