Typeahead.js - search in multiple property values
http://stackoverflow.com/questions/21850707/typeahead-js-search-in-multiple-property-values
by Ben Smith
HTML
<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<input type="text" id="search-input">
JavaScript
var data = [{
title: "some title here1",
desc: "some option here1",
category: [{
name: "category 1"
}, {
name: "categoy 2"
}]
}, {
title: "some title here2",
desc: "some option here2",
category: [{
name: "category 1"
}, {
name: "categoy 2"
}]
}];
var titles = new Bloodhound({
datumTokenizer: function (data) {
return Bloodhound.tokenizers.whitespace(data.title);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: data
});
var descs = new Bloodhound({
datumTokenizer: function (data) {
return Bloodhound.tokenizers.whitespace(data.desc);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: data
});
var getCategories = function (data) {
var cats = [];
data.forEach(function (item) {
item.category.forEach(function (it) {
// Note that in a final soluton you'd want to de-dupe the category items
cats.push(it);
});
});
return cats;
};
var categories = getCategories(data);
var cats = new Bloodhound({
datumTokenizer: function (data) {
return Bloodhound.tokenizers.whitespace(data.name);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: categories
});
titles.initialize();
descs.initialize();
cats.initialize();
$('#search-input').typeahead({
highlight: true
}, {
name: 'titles',
displayKey: 'title',
source: titles.ttAdapter()
}, {
name: 'descs',
displayKey: 'desc',
source: descs.ttAdapter()
}, {
name: 'cats',
displayKey: 'name',
source: cats.ttAdapter()
});