Given the following data structure
var things = [{ "name": "thing1", "sex": "male"},
{ "name": "thing2", "sex": "female"}];
I would like to be able to search that array of objects and pull out a particular object.
I currently have the following code written
function selectElementByName (name) {
var returnObject;
for (var i = 0; i < things.length; i++) {
if (things[i].name === name) {
returnObject = things[i];
}
}
if ( returnObject === undefined) {
console.log("Object not found");
}
return returnObject;
}
JsFiddle can be found here
Is there a more efficient way of doing this?
You can make an early exit when an object is found, so that you don’t have to loop through the rest of the array:
(This will however change the behaviour if there are duplicates, so that it returns the first object found instead of the last.)
If the names are unique, you could use them as key and store the objects in an object instead of in an array:
Then you wouldn’t need to loop to find an object:
If you need the objects in an array, you could still create an index for searching if the array doesn’t change so often:
Now you can use the index to find the object:
As you have to update or recreate the index as soon as the array changes, this would only be usedful if you do searches in the array much more often than you change the array.