Say I have an object:
userInfo
And I want to search each node of userInfo to see if the key 'username' has a value equal to foo.
userInfo[x].username == "foo"
Is there a better way of doing the following?
var matchFound = false;
for (var i = 0, len = userInfo.length; i < len; i++)
matchFound = userInfo[i].username == "foo";
There isn't really a better (more efficient) way without introducing another data structure. The answer really depends on your usage but you could do a few different things:
Create separate 'indexes' using hashes. These structures would map keys to the items or the index in the source array. JavaScript objects/hashes support key based lookup and should be efficient.
userinfo[x].username = "foo";
// Index the objects
usersByName = {};
usersByName["foo"] = userinfo[x];
// -- OR -- index the array indices
var usersByName["foo"] = x;
// Test for key
"foo" in usersByName; // true
You'll have to put in a little more work to maintain consistency between the index and the source array. It's probably best to wrap both in another object to manage the contents of both. This approach is nice if there are multiple fields that you want to look objects up by.
If you don't care about the order of the collection you could just change the whole thing to a hash and index by username
var userinfo = {};
userinfo["foo"] = {username: "foo", firstName: "Foo", lastName: "Bar"};
One thing to think about, though, is if the efficiency gains are going to outweigh the increased code complexity of maintaining indexes. If you aren't doing a lot of searches and you don't have tons of items in the userinfo collection it may make more sense to just write a general use searching function or use a library like what Philip Schweiger was mentioning.
function findObjectByAttribute (items, attribute, value) {
for (var i = 0; i < items.length; i++) {
if (items[i][attribute] === value) {
return items[i];
}
}
return null;
}
var userinfo = [];
userinfo[0] = {username: "foo"};
console.log(findObjectByAttribute(userinfo, "username", "foo"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With