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

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, use some 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 */
}

or the equivalent (in this case) find:

if (vendors.find(e => e.Name === 'Magenic')) {
  /* same result as above, but a different function return type */
}

And you can even get the position of that element by using findIndex:

const i = vendors.findIndex(e => e.Name === 'Magenic');
if (i > -1) {
  /* vendors contains the element we're looking for, at index "i" */
}

And 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 */
}

Leave a Comment