I people, i need help , i dont know how to handle the object to get what I need using vanilla. I need group by "type" for each "elem", and sum price and discount values, and return them in an array. I would appreciate if someone could explain to me how to approach the transformation.
I have this object
{
"w_elem": [
{
"elem": [
{"type": "type_a","price": "100","discount": "10"},
{"type": "type_b","price": "120","discount": "12"},
{"type": "type_a","price": "165","discount": "10"}
],
"user": "1001",
"userType": "A"
},
{
"elem": [
{"type": "type_a","price": "50","discount": "5"},
{"type": "type_b","price": "15","discount": "0"}
],
"user": "1011",
"userType": "B"
},
{
"elem": [
{"type": "type_a","price": "20","discount": "5"},
{"type": "type_b","price": "15","discount": "0"}
],
"user": "1011",
"userType": "B"
}
]
}
Imust return the following array
[
{"type": "type_a","price": "335","discount":"30"},
{"type":"type_b","price": "150","discount": "12"}
]
i tried the following but im not able to understand.
let helper = {};
const data = newArr.reduce((acc, currElem) => {
currElem.elem.forEach(item => {
if(!helper[currElem.type]) {
helper[currElem.type] = Object.assign({}, currElem);
acc.push(helper[currElem.type])
}else{
helper[currElem.type].price += currElem.price;
helper[currElem.type].discount += currElem.discount;
}
})
return acc;
}, [])