javascript 按js中的两个不同键分组

x7yiwoj4  于 2023-01-01  发布在  Java
关注(0)|答案(2)|浏览(121)

我使用reduce按照每个查询的Id对信息进行分组。

var data = [
   {Id: "552", valor:  "50.00", Descricao: "Fraldas", },
   {Id: "552", valor: "35.00", Descricao: "Creme", },
   {Id: "545", valor: "23.00", Descricao: "Caneta", },
   {Id: "545",  valor: "15.00", Descricao: "Caderno", },
   {Id: "562", valor: "23.00", Descricao: "Caneta", },
   {Id: "562",  valor: "15.00", Descricao: "Caderno", },
   {Id: "562", valor: "23.00", Descricao: "Caneta", },
   {Id: "562",  valor: "15.00", Descricao: "Caderno", },
];

var data1 = [
   {Id: "552", valor:  "50.00", Descricao: "camisola", },
   {Id: "562", valor: "35.00", Descricao: "calças", },
];

var data2 = [
   {Id: "552", Responsavel: "antonio", },
   {Id: "545", Responsavel: "Pedro", },
   {Id: "562", Responsavel: "Amélia", },
   {Id: "562", Responsavel: "Maria", },
];

var results = data.concat(data1).concat(data2).reduce(function(results, item) {
        var id = item.Id || item.Id || item.Id; 
        (results[id] = results[id] || []).push(item);
        return results;
      }, {});
      
$(document).on('click', '.dad-pagamento', function() {
  var linha = ``;
  Object.keys(results).forEach(id => {
  Object.keys(results[id]).forEach(c => {
    Responsavel = results[id][c].Responsavel;
  })
    linha += `<p class="taman" style="text-align:left"> ${Responsavel}</p>
    
              <div class="teste">
              <table class="align-middle mb-0 table table-borderless table-striped table-hover" border="1">
              
              <thead>
                <tr>
                  <th class="text-center">Nº Recibo</th>
                  <th class="text-center">Valor</th>
                  <th class="text-center">Descrição</th>
                </tr>
               </thead>                              
               <tbody>`;
    results[id].forEach(item => {
      var idValue = item.Id || item.Id;
      var valor = item.valor;
      var descricao = item.Descricao;
      linha += `<tr>
                   <td class="text-center text-muted"> ${idValue}</td>
                   <td class="text-center text-muted"> ${valor}</td>
                   <td class="text-center text-muted"> ${descricao}</td>
                 </tr>`;
    })
    linha += `</tbody></table></div>`;
  });
  $('#minhaDiv3').show();
  $(".pagmfalta").html(linha);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" tabindex="0" class="dropdown-item btn-show dad-pagamento" href="s3" data-element="#minhaDiv3">Teste</button>

<section id="s3">
  <div style="display:none" id="minhaDiv3">
    <button type="button" tabindex="0" class="dropdown-item" id="btnPrint" style="text-align:right;">Print</button>

        <div class="row pagmfalta">

      </div>
  </div>
</section>

如果你注意到我有两个人负责id 562,Amelia和Maria。但是当我返回数据时,它只为Maria返回一个表。我想要的是为Amelia和Maria返回两次相同的表。由于有两个不同的人负责,我打算在这些情况下,如果有多个人负责,它会根据需要返回相同的表多次。根据负责人的数量。

bqf10yzr

bqf10yzr1#

您不仅可以按id分组,还可以按名称分组,并使用这些字段的结果对象作为结果的键。

const arr = new Map();
rawRecords.forEach((rawRecord) => {
    const groupFieldsKey = JSON.stringify({id,name});
    const aggregatedValues = this._updateAggregateObject(rawRecord, arr.get(groupFieldsKey));
    arr.set(groupFieldsKey, aggregatedValues);
});

好吧。我们来编码一下。

const data = [
   {id: "552", value: "50.00", description: "Fraldas", },
   {id: "552", value: "35.00", description: "Creme", },
   {id: "545", value: "23.00", description: "Caneta", },
   {id: "545", value: "15.00", description: "Caderno", },
   {id: "562", value: "23.00", description: "Caneta", },
   {id: "562", value: "15.00", description: "Caderno", },
   {id: "562", value: "23.00", description: "Caneta", },
   {id: "562", value: "15.00", description: "Caderno", },
];

const data1 = [
   {id: "552", value: "50.00", description: "camisola", },
   {id: "562", value: "35.00", description: "calças", },
];

const data2 = [
   {id: "552", responsible: "antonio", },
   {id: "545", responsible: "Pedro", },
   {id: "562", responsible: "Amélia", },
   {id: "562", responsible: "Maria", },
];

const rawRecords = data.concat(data1).concat(data2);

const aggregateRawRecords = (recordsToProcess, accumulateObject, counter = 0) => {
    const copyAccumulateObject = {...accumulateObject
    };
    const notProcessedRawRecords = recordsToProcess.reduce((notProcessedResults, rawRecord) => {
        let processed = true;
        if (!rawRecord.responsible) {
            processed = !Object.keys(copyAccumulateObject)
            .filter(i => JSON.parse(i).id === rawRecord.id)
            .map(item => copyAccumulateObject[item].stuff.push({
                value: rawRecord.value,
                description: rawRecord.description,
            })).length ? false: true;
        } else {
            const groupFieldsKey = JSON.stringify({
                id: rawRecord.id,
                responsible: rawRecord.responsible,
            });
            copyAccumulateObject[groupFieldsKey] = {
                stuff: [],
            };
        }
        return processed ? notProcessedResults: [...notProcessedResults, rawRecord];
    },
    []);

    if (notProcessedRawRecords.length && !counter) {
        return aggregateRawRecords(notProcessedRawRecords, copyAccumulateObject, 1)
    } else {
        return Object.keys(copyAccumulateObject).map(item => {
            return {...JSON.parse(item),
                ...copyAccumulateObject[item]
            };
        });
    }
};

console.log(aggregateRawRecords(rawRecords, {}));
drkbr07n

drkbr07n2#

要为Amelia和Maria返回同一个表两次,我使用了以下步骤。
1.连接datadata1数组。
1.迭代data2数组。
1.对results阵列使用filter方法。
1.将HTML表添加到.pagmfalta div。
代码是用纯JavaScript编写的。

var data = [
    { Id: "552", valor: "50.00", Descricao: "Fraldas", },
    { Id: "552", valor: "35.00", Descricao: "Creme", },
    { Id: "545", valor: "23.00", Descricao: "Caneta", },
    { Id: "545", valor: "15.00", Descricao: "Caderno", },
    { Id: "562", valor: "23.00", Descricao: "Caneta", },
    { Id: "562", valor: "15.00", Descricao: "Caderno", },
    { Id: "562", valor: "23.00", Descricao: "Caneta", },
    { Id: "562", valor: "15.00", Descricao: "Caderno", },
];

var data1 = [
    { Id: "552", valor: "50.00", Descricao: "camisola", },
    { Id: "562", valor: "35.00", Descricao: "calças", },
];

var data2 = [
    { Id: "552", Responsavel: "antonio", },
    { Id: "545", Responsavel: "Pedro", },
    { Id: "562", Responsavel: "Amélia", },
    { Id: "562", Responsavel: "Maria", },
];

var results = data.concat(data1);

document.querySelector(".dad-pagamento").addEventListener("click", clickHandler);

function clickHandler() {
    // Sort person list by Id value
    data2.sort(function (a, b) {
        return a.Id - b.Id;
    });

    data2.forEach(function (person) {
        var id = person.Id;
        var filteredData = results.filter(d => d.Id === id);
        addHtml(person.Responsavel, filteredData);
    });
}

function addHtml(responsavel, filteredData) {

    var html = "";

    html += `<p class="taman" style="text-align:left"> ${responsavel}</p>
    
              <div class="teste">
              <table class="align-middle mb-0 table table-borderless table-striped table-hover" border="1">
              
              <thead>
                <tr>
                  <th class="text-center">Nº Recibo</th>
                  <th class="text-center">Valor</th>
                  <th class="text-center">Descrição</th>
                </tr>
               </thead>                              
               <tbody>`;

    filteredData.forEach(function (data) {
        html += `<tr>
                   <td class="text-center text-muted"> ${data.Id}</td>
                   <td class="text-center text-muted"> ${data.valor}</td>
                   <td class="text-center text-muted"> ${data.Descricao}</td>
                 </tr>`;
    });

    html += `</tbody></table></div>`;

    document.querySelector(".pagmfalta").innerHTML += html;
}
<button type="button" tabindex="0" class="dropdown-item btn-show dad-pagamento" href="s3" data-element="#minhaDiv3">Teste</button>
<div class="row pagmfalta"></div>

相关问题