Search code examples
jquerybootstrap-typeaheadtypeahead.jshogan.js

How to preprocess typeahead.js json results before passing to templating (hogan.js)?


typeahead.js works nice when the results being returned will be an array:

  var simpleCountriesList = [
     "Andorra",
     "United Arab Emirates",
     "Afghanistan",
     "Antigua and Barbuda"
  ];

In my case, there is an array of objects but it is wrapped in an object like this:

  var countryObjectsWrappedInResults = {
   "results":[
      {
         "name":"Andorra"
      },
      {
         "name":"United Arab Emirates"
      },
      {
         "name":"Afghanistan"
      },
      {
         "name":"Antigua and Barbuda"
      }
   ]
};

or

{
   "maintainers":[
      {
         "name":"Jake Harding",
         "url":"https://twitter.com/JakeHarding"
      },
      {
         "name":"Tim Trueman",
         "url":"https://twitter.com/timtrueman"
      },
      {
         "name":"Veljko Skarich",
         "url":"https://twitter.com/vskarich"
      }
   ]
}

I created a small jsbin to illustrate the problem with both local and remote: http://jsbin.com/OseWeKA/5/edit

I'm migrating from bootstrap typeahead where I was able to use updater to pop the array out of results. What is the equivalent for twitter.js?


Solution

  • Add a 'filter:' to your remote dataset. Something like:

    remote: {
        url: '...',
        filter: function (response) {
            retval = [];
            for (var i = 0;  i < response.maintainers.length;  i++) {
                retval.push(response.maintainers[i].name);
            }
            return retval;
        },
    }
    

    filter transforms your remote response into an array of datums.

    Regardless, your fiddle doesn't work because your server does not support JSONP, where as you clearly specify dataType: "jsonp". Your server also returns text/plain as the Content-Type, where as is should return a script. I assume there are not real issues in your "live" system.