There isn't any need to reinvent the wheel loop, at least not explicitly.
Use some as it allows the browser to stop as soon as one element is found that matches:
if (vendors.some(e => e.Name === 'Magenic')) {
// We found at least one object that we're looking for!
}
or the equivalent (in this case) with find, which returns the found object instead of a boolean:
if (vendors.find(e => e.Name === 'Magenic')) {
// Usually the same result as above, but find returns the element itself
}
If you'd like to get the position of that element, use findIndex:
const i = vendors.findIndex(e => e.Name === 'Magenic');
if (i > -1) {
// We know that at least 1 object that matches has been found at the index i
}
If you need to get all of the objects that match:
if (vendors.filter(e => e.Name === 'Magenic').length > 0) {
// The same result as above, but filter returns all objects that match
}
If you need compatibility with really old browsers that don't support arrow functions, then your best bet is:
if (vendors.filter(function(e) { return e.Name === 'Magenic'; }).length > 0) {
// The same result as above, but filter returns all objects that match and we avoid an arrow function for compatibility
}
Answer from CAFxX on Stack OverflowVideos
There isn't any need to reinvent the wheel loop, at least not explicitly.
Use some as it allows the browser to stop as soon as one element is found that matches:
if (vendors.some(e => e.Name === 'Magenic')) {
// We found at least one object that we're looking for!
}
or the equivalent (in this case) with find, which returns the found object instead of a boolean:
if (vendors.find(e => e.Name === 'Magenic')) {
// Usually the same result as above, but find returns the element itself
}
If you'd like to get the position of that element, use findIndex:
const i = vendors.findIndex(e => e.Name === 'Magenic');
if (i > -1) {
// We know that at least 1 object that matches has been found at the index i
}
If you need to get all of the objects that match:
if (vendors.filter(e => e.Name === 'Magenic').length > 0) {
// The same result as above, but filter returns all objects that match
}
If you need compatibility with really old browsers that don't support arrow functions, then your best bet is:
if (vendors.filter(function(e) { return e.Name === 'Magenic'; }).length > 0) {
// The same result as above, but filter returns all objects that match and we avoid an arrow function for compatibility
}
2018 edit: This answer is from 2011, before browsers had widely supported array filtering methods and arrow functions. Have a look at CAFxX's answer.
There is no "magic" way to check for something in an array without a loop. Even if you use some function, the function itself will use a loop. What you can do is break out of the loop as soon as you find what you're looking for to minimize computational time.
var found = false;
for(var i = 0; i < vendors.length; i++) {
if (vendors[i].Name == 'Magenic') {
found = true;
break;
}
}