A typical JSON document containing name and identifier pairs will look like this:
[ { "id": 1 "name": "firstName" }, { "id": 2 "name": "secondName" } ]
The strategy here is to create an object literal that maps names to identifiers when parsing the result, but only using the name to populate typeahead:
var productNames = new Array(); var productIds = new Object(); $.getJSON( '/getAjaxProducts', null, function ( jsonData ) { $.each( jsonData, function ( index, product ) { productNames.push( product.name ); productIds[product.name] = product.id; } ); $( '#product' ).typeahead( { source:productNames } ); } );
Once the user selects an element from the head type, you can refer to the selected element with:
$( '#product' ).val()
and you can get the id associated with the selected item with:
productIds[$( '#product' ).val()]
From your question, it looks like your JSON document might be structured a little differently, so you will change the parsing as needed, but the same general strategy applies.
source share