Coder Perfect

How can I tell if a Javascript array has an object with a property identical to a certain value?

Problem

I have an array that looks like this:

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

How do I see if “Magenic” is present in this array? I don’t want to loop until it’s really necessary. I could be working with a couple thousand records.

Asked by David Lozzi

Solution #1

There’s no need to reinvent the wheel loop, at least not explicitly (modern browsers only):

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

or, better yet, because it allows the browser to stop searching as soon as one matching element is found, it will be faster:

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

EDIT: If you need to work with old browsers, your best bet is to use:

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

Answered by CAFxX

Solution #2

This answer was written in 2011, before most browsers had array filtering methods and arrow functions. Check out CAFxX’s response.

Without a loop, there is no “magic” way to check for something in an array. Even if you utilize a function, the function will employ a loop of its own. To reduce computational time, you can break out of the loop as soon as you locate what you’re looking for.

var found = false;
for(var i = 0; i < vendors.length; i++) {
    if (vendors[i].Name == 'Magenic') {
        found = true;
        break;
    }
}

Answered by Alex Turpin

Solution #3

There’s no need for a loop. Three approaches come to mind:

Array.prototype.some()

This is the most precise response to your question, namely, “check if anything exists,” which implies a bool result. If there are any ‘Magenic’ objects, this will be true; otherwise, it will be false:

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

Array.prototype.filter()

Even if there is just one ‘Magenic’ object, this will produce an array of all of them (a one-element array):

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

You can’t convert this to a boolean because an empty array (with no ‘Magenic’ items) is still true. So in your conditional, just use magenicVendors.length.

Array.prototype.find()

The first ‘Magenic’ object (or undefined if none exist) will be returned:

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

This results in a boolean yes (any object is truthy, undefined is falsy).

Note that instead of vendor, I’m using vendor[“Name”]. Because of the strange case of the property name, it was given a name.

Note 2: When testing the name, there’s no reason to use loose equality (==) instead of stringent equality (===).

Answered by boxtrain

Solution #4

The accepted solution still works, however we now have ECMAScript 6 native methods [Array.find][1] and [Array.some][2] that do the same result.

Array.some

Make use of some If you merely need to know if an element exists, a true/false judgment will suffice.

Quoting MDN:

Array.find

If you want to get the matched object from an array, use find; otherwise, undefined is returned.

Quoting MDN:

var arr = [];
var item1 = {
    id: 21,
    label: 'Banana',
};
var item2 = {
    id: 22,
    label: 'Apple',
};
arr.push(item1, item2);

/* note : data is the actual object that matched search criteria 
  or undefined if nothing matched */

var data = arr.find(function(ele) {
    return ele.id === 21;
});

if (data) {
    console.log('found');
    console.log(data); // This is entire object i.e. `item` not boolean
}


/* note : doesExist is a boolean thats true or false depending on of whether the data was found or not */
var doesExist = arr.some(function(ele) {
    return ele.id === 21;
});


See my jsfiddle link for further information. Mozilla has a polyfill for Internet Explorer.

Answered by TeaCoder

Solution #5

Here’s how I’d go about it.

const found = vendors.some(item => item.Name === 'Magenic');

array. The some() method returns a true if there is at least one element in an array that fits criteria. From here, you have the option of:

if (found) {
// do something
} else {
// do something else
}

Answered by Mirza Leka

Post is based on https://stackoverflow.com/questions/8217419/how-to-determine-if-javascript-array-contains-an-object-with-an-attribute-that-e