How do I list objects for Typeahead.js and / or with Bloodhound engine?

I'm having a hard time figuring out how to display a list of objects using typeahead with a json file as source. None of my details are displayed.

I want to list names and use other attributes for other things when selected.


    {"name": "John Snow", "id": 1},
    {"name": "Joe Biden", "id": 2},
    {"name": "Bob Marley", "id": 3},
    {"name": "Anne Hathaway", "id": 4},
    {"name": "Jacob deGrom", "id": 5}



$(document).ready(function() {
    var names = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.whitespace("name"),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: {
          url: '../data/test.json'

    $('#test .typeahead').typeahead({
        name: 'names',
        displayKey: 'name',
        source: names.ttAdapter()



<div id="test">
    <input class="typeahead" type="text">


** And if someone can explain to me what datumTokenizer and queryTokenizer are, that would be awesome **


source to share

2 answers

The JSON file contains an array of JSON objects, but the Bloodhound proposal engine expects an array of JavaScript objects.

Hence, you need to add a filter to your prefetch declaration:

prefetch: {
 url: '../data/test.json',
 filter: function(names) {
   return $.map(names, function(name) { 
    return { name: name };


With regard to the "datumTokenizer", the goal is to define how the data (ie, sentence values) should be marked. It is these markers that are then used to match the input query.

For example:



This takes a value (in your case a name value) and splits it into two tokens, for example. "Bob Marley" will be split into two tokens "Bob" and "Marley".

You can see how the whitespace tokenizer works by looking at the typeahead source :

function whitespace(str) {
 str = _.toStr(str);
 return str ? str.split(/\s+/) : [];


Notice how it breaks up databases using a regular expression for spaces (\ s + ie one or more occurrences of spaces).

Likewise, the "queryTokenizer" also defines how to tokenize the search query. Again, in your example, you are using the whitespace tokenizer, so the search term "Bob Marley" will return the data "Bob" and "Marley".

Hence, with certain markers, if you were looking for "Marley", a match was found for "Bob Marley".



I have a simpler version that you did right, except for one small mistake. You can actually use an array of objects as you showed.

Replace displayKey: 'name'

with display: 'name'

and it should work.

So the complete typeahead function would look like

$('#test .typeahead').typeahead({
    name: 'names',
    display: 'name',
    source: names.ttAdapter()




All Articles