【问题标题】:select2 optgroup ajax json fomatselect2 optgroup ajax json格式
【发布时间】:2018-08-18 06:36:53
【问题描述】:

我想将返回的 json 数据按libelle 分组,我最终得到以下结果 脚本:

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

输出:

有没有可能在不重复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"}]

【问题讨论】:

标签: json ajax laravel jquery-select2


【解决方案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,
         }
    })       
 };

【讨论】:

  • 你的意思是:processResults: function (data) { return { results: $.map(groupBy(data,'libelle'), function (item,key) { var children = item; return {文本:键,孩子:item.nom +' '+ item.prenom, } }) }; },
  • 我只得到 optgroup 数据,没有显示子项
  • console.log 项在return 语句之前会记录什么?
  • (14) [{...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {... }, {...}, {...}, {...}, {...}] 0 : {id: 1, nom: "jhon", prenom: "M", libelle: "Laboratoire Arithmétique calcul Scientifique et Applications 2016 - 2019 « FSO »"}
  • 在最后一个答案之后,我确实更改了结果:$.map(data, function (item,key) { 到结果:$.map(groupBy(data,'libelle'), function (item, key) { 现在一切正常,谢谢 Sérgio Reis
猜你喜欢
  • 2016-12-10
  • 1970-01-01
  • 2020-04-14
  • 2013-05-12
  • 1970-01-01
  • 1970-01-01
  • 2019-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多