select2 optgroup ajax json fomat

时间:2018-03-09 16:21:09

标签: json ajax laravel jquery-select2

我希望按libelle对返回的json数据进行分组。我最终得到以下内容 脚本:

$('.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
        }
});

输出: enter image description here

是否有可能让小组正常工作而不重复libelle

JSON输出:

[{"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"}]

1 个答案:

答案 0 :(得分:1)

似乎你正在寻找类似这样的东西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,
         }
    })       
 };