使用将具有相同值的数据组合在一起的脚本触发我获取的数据

triggering my fetched data with my script that combines data with the same value

我的目标是将具有相同级别的 2 个数组合并为 1 个数组。

For example i have testing 1 = level 1 and testing 4 = level 1. They'll be joined in 1 array because they have the same level.

我提供的以下脚本是将 2 个数组合并为 1 个数组(如果它们具有相同的级别)。我怎样才能达到我上面所说的目标?感谢你们。我在下面提供了我的代码和图片。

[An Image of what I'm fetching] [An Image of my target when 2 scripts are joined]

Ajax:

  var ajaxResult=[]; // the pushed data will be saved here
    var save_method; 
    var table;
    var base_url = '<?php echo base_url();?>';
     
    $(document).ready(function() {
     
        //datatables
        table = $('#entry_list').DataTable({ 
            dom: 'lBfrtip',
            buttons: [
                'print', 'csv', 'copy', 'excel', 'pdfHtml5'
            ],
           
            "processing": false, 
            "serverSide": true,     
            "order": [], 
            
     
        
            "ajax": {
                "url": "<?php echo site_url('controller/fetch_players')?>",
                 "type": "POST",
                 async:true,
                 dataType: "json", 
                 
             
                 success: function(data){
             
                 ajaxResult.push(data); // I'm pushing my data to my ajaxResult variable
       
        
       console.log(ajaxResult);
                  
               
               
                },
                
            },
     
           
            "columnDefs": [
                { 
                    "targets": [ 0 ], 
                    "orderable": false,
                },
                { 
                    "targets": [ -1 ], 
                    "orderable": false, 
                },
     
            ],
     
        });
});

脚本:

//script for combiningng data in 1 array if they have the same level. 
    

const ajaxResult= [] // I'm calling here what I fetched on my ajax.
        
        const matching = (list, keyGetter) => {
            let mapping = {};
            const map = new Map();
            list.forEach((item) => {
                const key = keyGetter(item);
                const collection = map.get(key);
                if (!collection) {
        
                    map.set(key, [item]);
                } else {
        
                    collection.push(item);
                }
            });
        
            Array.from(map).map(([key, value]) => Object.assign(mapping, { [key]: value }));
            return mapping
        }
        
        const result = matching(ajaxResult, ({ level}) => { return level});
        
        console.log("RESULT", result);  // when i do console.log, the result me be testing 1 and testing 4 in 1 array, so is testing 2 and testing 4

您可以使用 array.reduce 来实现所需的行为。

const source = [
    {id: 1, name: 'player1', level: 1},
    {id: 2, name: 'player2', level: 2},
    {id: 3, name: 'player3', level: 3},
    {id: 4, name: 'player4', level: 1},
    {id: 5, name: 'player5', level: 2},
    {id: 6, name: 'player6', level: 3},
]

const combine = (source) => {
    return source.reduce((acc,curr) => {
        if(acc[curr.level]) 
            acc[curr.level].push(curr);
        else
            acc[curr.level] = [curr];   
        return acc;
    },{})
}

console.log('Result', combine(source));

解释:

reducer 遍历和数组,对于每次迭代,它可以保存上一次计算的结果。使用这个想法,我们首先检查我们是否有计算级别的数组,如果有,我们只是将当前对象推入数组。如果不是,我们创建一个新数组,将当前对象作为第一个元素。

P.S:我建议在每次迭代时添加日志来检查 acccurr 的值,以便更好地理解这一点。

编辑:展示如何使用 Ajax 响应:

let ajaxResult = []; // the pushed data will be saved here
let save_method;
let table;
let base_url = "<?php echo base_url();?>";
let result = [];

const combine = (source) => {
  return source.reduce((acc, curr) => {
    if (acc[curr.level])
      acc[curr.level].push(curr);
    else
      acc[curr.level] = [curr];
    return acc;
  }, {})
}

$(document).ready(function() {
  //datatables
  table = $("#entry_list").DataTable({
    dom: "lBfrtip",
    buttons: ["print", "csv", "copy", "excel", "pdfHtml5"],

    processing: false,
    serverSide: true,
    order: [],

    ajax: {
      url: "<?php echo site_url('controller/fetch_players')?>",
      type: "POST",
      async: true,
      dataType: "json",

      success: function(data) {
        ajaxResult.push(data); // I'm pushing my data to my ajaxResult variable
        result = combine(ajaxResult); // Cleanup your data here. 
      },
    },

    columnDefs: [{
        targets: [0],
        orderable: false,
      },
      {
        targets: [-1],
        orderable: false,
      },
    ],
  });
});