Typeahead.js - Search in multiple property values

Iladarsda picture Iladarsda · Feb 18, 2014 · Viewed 16.9k times · Source

Please see example below.

JSFiddle: http://jsfiddle.net/R7UvH/2/

How do I make typeahead.js (0.10.1) search for matches in more than one property value? Ideally, within whole data (data.title, data.desc and in all data.category[i].name)

 datumTokenizer: function(data) {
     // **search in other property values; e.g. data.title & data.desc etc..**
     return Bloodhound.tokenizers.whitespace(data.title);
 },

Whole example:

var data = [{
    title: "some title here",
    desc: "some option here",
    category: [{
        name: "category 1",
    }, {
        name: "categoy 2",
    }]
},
{
    title: "some title here",
    desc: "some option here",
    category: [{
        name: "category 1",
    }, {
        name: "categoy 2",
    }]
}];

var posts = new Bloodhound({
    datumTokenizer: function(data) {
        // **search in other property values; e.g. data.title & data.desc etc..**
        return Bloodhound.tokenizers.whitespace(data.title);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: data
});
posts.initialize();

$('#search-input').typeahead({
    highlight: true
}, {
    name: 'Pages',
    displayKey: 'title',
    source: posts.ttAdapter(),
    templates: {
        header: '<h3>Pages</h3>'
    }
});

Answer

Neelabh picture Neelabh · Sep 29, 2014

Typeahead 0.10.3 added "support to object tokenizers for multiple property tokenization."

So, your example becomes

var posts = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('title', 'desc'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: data
});

However, I don't think this will work for properties nested inside, that is, the data.category object in your case.

As a side note, if you are using prefetched data, be sure to clear the local storage first, otherwise the new tokenizer won't take effect (Because datumTokenizer is used when adding to the search index, and if data is already present in localStorage, then the search index will not be updated). I was stuck on this for a while!