我使用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返回两次相同的表。由于有两个不同的人负责,我打算在这些情况下,如果有多个人负责,它会根据需要返回相同的表多次。根据负责人的数量。
2条答案
按热度按时间bqf10yzr1#
您不仅可以按id分组,还可以按名称分组,并使用这些字段的结果对象作为结果的键。
好吧。我们来编码一下。
drkbr07n2#
要为Amelia和Maria返回同一个表两次,我使用了以下步骤。
1.连接
data
和data1
数组。1.迭代
data2
数组。1.对
results
阵列使用filter
方法。1.将HTML表添加到
.pagmfalta
div。代码是用纯JavaScript编写的。