I intend to add the value of the valor variable. For that I’m using this code:
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: "602", valor: "23.00", Descricao: "Caneta", },
{Id: "602", valor: "15.00", Descricao: "Caderno", },
];
var results = data.reduce(function(results, org) {
(results[org.Id] = results[org.Id] || []).push(org);
return results;
}, {});
$(document).on('click', '.dad-pagamento', function() {
var linha = ``;
Object.keys(results).forEach(i => {
linha += `totalizando`;
var ValorPacote = 0;
Object.keys(results[i]).forEach(b => {
valor = results[i][b].valor;
ValorPacote = parseFloat(valor).toFixed(2) + parseFloat(valor).toFixed(2);
linha += `${ValorPacote}`;
})
})
$('#minhaDiv1').show();
$(".pagmfalta").html(linha);
});
<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" >Teste</button>
<section id="s1">
<div style="display:none" id="minhaDiv1">
<button type="button" tabindex="0" class="dropdown-item" id="btnPrint" style="text-align:right;">Print</button>
<div id="printThis">
<div class="row pagmfalta">
</div>
</div>
</div>
</section>
But the problem is that when I run the code it is not adding and without, repeating the value twice. Can anyone help?
>Solution :
try this
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: "602", valor: "23.00", Descricao: "Caneta", },
{Id: "602", valor: "15.00", Descricao: "Caderno", },
];
// Group the objects by their Id property
var results = data.reduce(function(results, org) {
(results[org.Id] = results[org.Id] || []).push(org);
return results;
}, {});
$(document).on('click', '.dad-pagamento', function() {
var linha = ``;
Object.keys(results).forEach(i => {
// Initialize the total value for each group
var ValorPacote = 0;
Object.keys(results[i]).forEach(b => {
// Convert the valor string to a number and add it to the total value
ValorPacote += parseFloat(results[i][b].valor);
});
// Add the total value for the group to the output string
linha += `Totalizando: ${ValorPacote.toFixed(2)} `;
});
$('#minhaDiv1').show();
$(".pagmfalta").html(linha);
});