0

I have autocomplete like this .

data[0] = {code:1,name:"jame"}
data[1] = {code:2,name:"el"}
data[2] = {code:3,name:"hey"}
.
.


$('#txtKeywd').autocomplete({
    source: data.name,
    autoFocus: true,
    delay: 500,
    minLength: 1
});

I could search by name so, I can get name like jame, el...

However what I want finally is code.

Now I made this code.

I can get final answer with it ,but it looks quite redundant and slow.

Do you have any good ideas??

var txt = $(txtKeywd).val();    
for (i in data.name){

    if (data.name[i] === txt){
        console.log(data.code[i]); // i can get the code here!!! but it takes time....
    }
}
whitebear
  • 11,200
  • 24
  • 114
  • 237

2 Answers2

0

If your names are unique, use an object hash, the lookup time is O(1).

You could structure it like:

var lookup = 
{
  jame: 1,
  hey: 3,
  el: 2,
  'a name with spaces': 87
};

var code = lookup['jame']; // gives 1

Note that:

var code = lookup['jaem']; // gives undefined

Also note that the lookup keys (the names) need to follow valid JavaScript variable naming conventions, otherwise you have to place them in quotes, double " " or single ' ', your choice

If you have to have an array of objects for your autocomplete to work, then you might have to use both, but generate the lookup from the array, like:

var lookup = {};
data.forEach(function(index)
{
  lookup[data[index].name] = data[index].code;
});

A few questions,

  1. How big is your array of data?
  2. Have you timed just the lookup time?
  3. If your list is small, are you doing anything else in your code that shouldn't be in the lookup routine?
  4. Is this the jQuery UI autocomplete you are using?

To optimize what you have a for loop would be much faster than a for in loop.

Also, I suspect your are using autocomplete so you get n results for each prefix the user has typed, in which case, the lookup will not work, therefore ... depending on your use case and the desired outcome, you might be better served using a different data structure completely ... maybe a trie Here is one that was prepared earlier. The author of JQuery has some ideas as well.

click2install
  • 980
  • 9
  • 23
0

You can use the event handler .change(): As the API says, the function handling this event will receive as a second parameter the selected item:

...
$('#txtKeywd').autocomplete({
    source: data.name,
    autoFocus: true,
    delay: 500,
    minLength: 1
}).change(function (event,item) {
    console.log(item.code);
});
Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59