At times, I often find myself needing to locate a specific object within an array of objects where the key I am searching for matches a particular value.
For instance:
var cars = [
{ id:23, make:'honda', color: 'green' },
{ id:36, make:'acura', color:'silver' },
{ id:18, make:'ford', color:'blue' },
{ id:62, make:'ford', color:'green' },
];
Let's say I want to access the entry with id=18.
Currently, my approach looks like this:
function select(key,val,arr){
for(var i in arr){
if(arr[i][key]==val) return(arr[i]);
}
return(null); // object not found in arr
}
var id = 18;
var car = select('id', id, cars);
// car = { id:18, make:'ford', color:'blue' }
However, this method feels cumbersome and lacks scalability. Retrieving a value from a large dataset can be quick if it's towards the beginning of the array or could take as many iterations as there are entries. Moreover, it seems inefficient when the desired value does not exist, as you end up iterating through all objects only to yield a null result.
Is there a more streamlined way to search an array or object for a value when the search criteria isn't aligned with the subject's keys?