JS - data manipulation on array of objects with property that contains array
Example array -
const arr = [
{
charge: [ { id: '1', qty: 10 }, { id: '2', qty: 20 } ],
totalCharge: 100,
qtySum: 50
},
{
charge: [ { id: '3', qty: 30 }, { id: '4', qty: 40 } ],
totalCharge: 70,
qtySum: 100
},
]
The math actions - (qty * totalCharge) / qtySum
Output (not real numbers) -
[
{
id: '1',
calcQty: 300,
},
{
id: '2',
calcQty: 250,
},
{
id: '3',
calcQty: 300
},
{
id: '4',
calcQty: 400
}
]
What I could not understand how to do is to separate the charge
and only then do the math I need. Because I need to use the same totalCharge
and qtySum
each time based on how many organs are in the charge
field, would love to get some help
You can use a combination of map
and flat
.
const arr = [
{
charge: [
{ id: "1", qty: 10 },
{ id: "2", qty: 20 },
],
totalCharge: 100,
qtySum: 50,
},
{
charge: [
{ id: "3", qty: 30 },
{ id: "4", qty: 40 },
],
totalCharge: 70,
qtySum: 100,
},
];
const res = arr
.map(({ charge, totalCharge, qtySum }) =>
charge.map(({ id, qty, stySum }) => ({
id,
calcQty: (totalCharge * qty) / qtySum,
}))
)
.flat();
console.log(res);
You can use forEach twice to get the math action done.
Try like below.
const arr = [
{
charge: [
{ id: "1", qty: 10 },
{ id: "2", qty: 20 },
],
totalCharge: 100,
qtySum: 50,
},
{
charge: [
{ id: "3", qty: 30 },
{ id: "4", qty: 40 },
],
totalCharge: 70,
qtySum: 100,
},
];
const output = [];
arr.forEach(({ charge, totalCharge, qtySum }) => {
charge.forEach(({ id, qty }) => {
output.push({ id, calcQty: (qty * totalCharge) / qtySum });
});
});
console.log(output);
You could map nested arrays and get a flat result.
const
array = [{ charge: [{ id: '1', qty: 10 }, { id: '2', qty: 20 }], totalCharge: 100, qtySum: 50 }, { charge: [{ id: '3', qty: 30 }, { id: '4', qty: 40 }], totalCharge: 70, qtySum: 100 }],
result = array.flatMap(({ charge, totalCharge, qtySum }) =>
charge.map(({ id, qty }) => ({
id,
calcQty: qty * totalCharge / qtySum
}))
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }