Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  119] [ 5]  / answers: 1 / hits: 19695  / 13 Years ago, tue, september 27, 2011, 12:00:00

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;

More From » loops

 Answers
15

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:




  1. 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.


  2. 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));

[#89893] Monday, September 26, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monetm

Total Points: 615
Total Questions: 103
Total Answers: 119

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
monetm questions
Fri, Feb 26, 21, 00:00, 3 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Sun, Jul 26, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;