I have an array of objects and I´d like to transsform it in a other.
I can do it with a for loop, but I´d like to use reduce.
How could I do it using reduce?
const arr=[
{ medico: "med1", rateio: "rat1", convenio: "conv1", subtotal: 10 },
{ medico: "med2", rateio: "rat2", convenio: "conv2", subtotal: 10 },
{ medico: "med2", rateio: "rat2", convenio: "conv2", subtotal: 20 },
{ medico: "med1", rateio: "rat1", convenio: "conv3", subtotal: 20 },
{ medico: "med1", rateio: "rat1", convenio: "conv3", subtotal: 25 },
{ medico: "med2", rateio: "rat3", convenio: "conv4", subtotal: 15 },
{ medico: 'med2', rateio: 'rat4', convenio: 'conv3', subtotal: 10 },
];
I need the next result:
const result=[
{medico: "med1", grantotals:[
{
rateio: "rat1",
grandtotals: [
{ convenio: "conv1", sum_subtotal: 10 },
{ convenio: "conv3", sum_subtotal: 45 }
]
}
]},
{medico: "med2", grantotals:[
{
rateio: "rat2",
grandtotals: [
{ convenio: "conv2", sum_subtotal: 30 },
]
},
{
rateio: "rat3",
grandtotals: [
{ convenio: "conv4", sum_subtotal: 15 },
]
},
{
rateio: "rat4",
grandtotals: [
{ convenio: "conv3", sum_subtotal: 10 },
]
}
]}
]
3
Answers
Using the
reduce()
method in JavaScript, Here below I demonstrate how to applyreduce()
to convert the arr array into the desired result array structure:reduce()
method is used to iterate over thearr
array and transform the data into the desired structure.obj
) in thearr
array. We check if there is an existingmedico
object in theacc
array using thefind()
method.medico
object is found, we continue searching for the existingrateio
object within thatmedico
object.rateio
object is found, we continue searching for the existingconvenio
object within thatrateio
object.convenio
object is found, we update thesum_subtotal
property by adding the subtotal value to it.convenio
object is not found, we create a newconvenio
object and push it into the grandtotals array within the existing rateio object.rateio
object is not found, we create a newrateio
object with the corresponding convenio object and push it into the grantotals array within the existing medico object.medico
object with the correspondingrateio
andconvenio
objects and push it into theacc
array.acc
array is returned as the result array. Is there anything else I can help you with?One approach is to fold your input into a format like this, using
reduce
:and rehydrating with your property names, by repeatedly using
Object.entries
and mapping the results. It turns out relatively straightforward:compressed
is the format above, which we create by what is essentially a nestedgroupBy
function. Then we return an object which works its way inward along the nested properties, usingObject.entries
to create the key-value pairs, and mapping those to simple objects.Added an explanation in the comments: