snippetjavascriptCritical
How to determine if a JavaScript array contains an object with an attribute that equals a given value
Viewed 0 times
arrayobjecthowwithattributedeterminevalueequalsgiventhat
Problem
I have an array like
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 of thousand records.
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 of thousand records.
Solution
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.
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;
}
}Code Snippets
var found = false;
for(var i = 0; i < vendors.length; i++) {
if (vendors[i].Name == 'Magenic') {
found = true;
break;
}
}Context
Stack Overflow Q#8217419, score: 388
Revisions (0)
No revisions yet.