Matriz de ejemplo -
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 }, ]Las acciones matemáticas - (qty * totalCharge) / qtySum
Salida (no números reales) -
[ { id: '1', calcQty: 300, }, { id: '2', calcQty: 250, }, { id: '3', calcQty: 300 }, { id: '4', calcQty: 400 } ] Lo que no pude entender cómo hacer es separar la charge y solo luego hacer los cálculos que necesito. Debido a que necesito usar el mismo totalCharge y qtySum cada vez en función de cuántos órganos hay en el campo de charge , me encantaría obtener ayuda.
Puede usar una combinación de map y 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);Puede usar forEach dos veces para realizar la acción matemática.
Prueba como a continuación.
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);Podría mapear matrices anidadas y obtener un resultado plano.
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; }