You can use the data and result functions in your ajax call to query, analyze and set your json data depending on your data.
Here is a small piece of code from my production code that does something similar to what you are asking:
$(".autocomplete-search").select2({ placeholder: "Pizza, Movies, etc...", minimumInputLength: 2, ajax: { url: '/find-suggestions.json', dataType: 'json', quietMillis: 250, data: function(params, page) { return { query: params, page: page }; }, results: function(data, page) { var more, search_all, searched_for; searched_for = $(".select2-search input").val(); search_all = [ { query: searched_for } ]; more = data.suggestions.stores.length >= 1; return { results: search_all.concat(data.suggestions.categories, data.suggestions.stores), more: more }; } } });
In data: I use the params value to pass the original value to my ajax api, and then in results: return the data; I can get the original input value ( searched_for ) and associate it with the other data below, parse it and concatenate, as shown in the example.
I donβt know how to give you the exact answer you are looking for, but not in more detail, but I believe that the code fragment illustrates the types of behavior that you are trying to execute. Also, I just noticed that @prollyGeek's answer came when I printed it, read the documents in the comments, and is also useful.
source share