1

i want to group returned json data by libelle i end up with the following script :

$('.membre').select2({
        placeholder: 'Select an item',
        ajax: {
          url: '/select2-autocomplete-ajax',
          dataType: 'json',
          delay: 250,
          data: function (params) {
            return {
              membre_id: params.term // search term

            };
          },
          processResults: function (data) {

            return {
              results:  $.map(data, function (item) {
                    return {

                        text: item.libelle,
                        children: [{
                        id: item.id,
                        text: item.nom +' '+ item.prenom
                        }]

                    }
                })

            };
          },
          cache: true
        }
});

Output : enter image description here

is there any possibility to make the group work properly without repeating the libelle ?

JSON output :

[{"id":1,"libelle":"Laboratoire Arithm\u00e9tique calcul Scientifique et Applications","nom":"jhon","prenom":"M"},{"id":2,"libelle":"Laboratoire Arithm\u00e9tique calcul Scientifique et Applications","nom":"JHON","prenom":"jhon"}]
Miloud BAKTETE
  • 2,404
  • 3
  • 19
  • 30

1 Answers1

1

Seems you're looking for something like this https://select2.org/data-sources/formats#grouped-data

// Add this somewhere before the ajax
var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};


processResults: function (data) {
   return {
      results:  $.map(data, function (item,key) {
         var children = [];
         for(var k in item){
             var childItem = item[k];
             childItem.text = item[k].nom +' '+ item[k].prenom;
             children.push(childItem);
         }
         return {
            text: key,
            children: children,
         }
    })       
 };
Sérgio Reis
  • 2,483
  • 2
  • 19
  • 32
  • do you mean : processResults: function (data) { return { results: $.map(groupBy(data,'libelle'), function (item,key) { var children = item; return { text: key, children: item.nom +' '+ item.prenom, } }) }; }, – Miloud BAKTETE Mar 09 '18 at 22:37
  • i'm getting only the optgroup data no childrens displayed – Miloud BAKTETE Mar 09 '18 at 23:24
  • What does it log when you console.log item before the return statement? – Sérgio Reis Mar 10 '18 at 09:42
  • (14) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0 : {id: 1, nom: "jhon", prenom: "M", libelle: "Laboratoire Arithmétique calcul Scientifique et Applications 2016 - 2019 « FSO »"} – Miloud BAKTETE Mar 10 '18 at 12:57
  • after the last answer i did change results: $.map(data, function (item,key) { to results: $.map(groupBy(data,'libelle'), function (item,key) { and now it's working fine thank you Sérgio Reis – Miloud BAKTETE Mar 10 '18 at 14:04