Bitz Bitz - 1 month ago 16
Javascript Question

Substring matching for multi property object in Twitter Typeahead

So the data looks like this before going into the substring matcher:

var datasource = [
{name: 'Activity One', id: '1'},
{name: 'Activity Two', id: '2'},
{name: 'Activity Three', id: '3'},
{name: 'Activity Four', id: '4'}
];


When it was a normal array of values

var datasource = { 'Activity One', 'Activity Two',...


It was simple to use twitter typeahead to match correctly, but now that there are multiple properties, I am not sure about how the substring matcher is supposed to work.

This is how Initialize the typeahead:

$(control)
.typeahead({
hint: true,
highlight: true,
minLength: 0
},
{
displayKey: "name",
name: "name",
source: substringMatcher(datasource)
});


Now, the string matches correctly on the initial click, but can't match it anymore using the substring matcher.

Here is the substring matcher:

var substringMatcher = function (strs) {
return function findMatches(q, cb) {
var matches = [];
var substrRegex = new RegExp(q, 'i');
$.each(strs,
function (i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};};


What do I need to change? I don't know how to refer to the *.name property.

Answer

Bloodhound does substring matching. As for accessing the properties, use

var ds = datasource.map(function(o) { return o.name; });