ciao!
grazie per la segnalazione.
partendo da uno degli esempi, questo funziona:
codice:
$(document).ready(function () {
const objArr = [
{editor: "bur", val: 1, val2: 10},
{editor: "bur", val: 2, val2: 10},
{editor: "mondadori", val: 9, val2: 1},
{editor: "oscar mondadori", val: 10, val2: 1}
];
const output = objArr.reduce((accumulator, cur) => {
let found = accumulator.find(elem => elem.editor === cur.editor);
if (found) {
found.val += cur.val;
found.val2 += cur.val2;
} else {
accumulator.push(cur);
}
return accumulator;
}, []);
console.log(output)
});
tornando invece al mio json, ho un problema banale sul campo prezzo.
nel json è unn stringa, e quindi non fa la somma corretta:
codice:
$(document).ready(function () {
let json = '[{"id":"204","title":"fondazione e terra","author_id":null,"author":"isaac asimov","editor_id":null,"editor":"oscar mondadori","price":"26.49","isbn":"88-04-32634-4","note":"usato"},{"id":"202","title":"l\'orlo della fondazione","author_id":null,"author":"isaac asimov","editor_id":null,"editor":"oscar mondadori","price":"30.99","isbn":"978-88-04-39816-5","note":"usato"},{"id":"217","title":"preludio alla fondazione","author_id":null,"author":"isaac asimov","editor_id":null,"editor":"mondadori","price":"27.90","isbn":"88-04-32450-3","note":"usato"}]';
var objArr = jQuery.parseJSON(json);
const output = objArr.reduce((accumulator, cur) => {
let found = accumulator.find(elem => elem.editor === cur.editor);
if (found) {
found.price += parseFloat(cur.price);
} else {
accumulator.push(cur);
}
return accumulator;
}, []);
console.log(output)
});
a parte questo, cmq sembra funzionare.