1

I have a json file which outputs

{"data": ["A", "B", "C", "D", ...]}

My typeahead.js script looks like

var engine = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: {
        url: 'list.json',
        filter: function(list) {
            return $.map(list, function(person) { return { name: person }; });
        }
    }
});

engine.initialize();

$('.typeahead').typeahead(null, {
    displayKey: 'name',
    source: engine.ttAdapter()
});

The typeahead.js script is activated correctly, but it interprets the data source as only one comma separated item instead of separate items. So instead of 'searching' through the elements "A", "B", "C" etc. it just gives me one suggestion "A, B, C, ...".

What is wrong with my script? I have followed the examples at http://twitter.github.io/typeahead.js/examples/.

If I change "name" to "value" both in datumTokenizer, filter and displayKey it wont get any items at all, but only output "undefined". I am pretty sure it's the filter option inside prefetch which doesn't work correctly.

Jamgreen
  • 10,329
  • 29
  • 113
  • 224
  • 1
    [This](http://stackoverflow.com/a/21533204/203371) answer, which gives a remote example, may help you. – Ben Smith Aug 25 '14 at 22:17

1 Answers1

0

In the filter function you are iterating over the properties of the object:

{"data": ["A", "B", "C", "D", ...]}

in this case, you are iterating over "data" only. For iterate over the items in "data", you should pass list.data to the filter function. In this way:

var engine = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: {
        url: 'list.json',
        filter: function(list) {
            return $.map(list.data, function(person) { return { name: person }; });
        }
    }
});
jloria
  • 94
  • 1
  • 5