I have an object that I map within a React component to render some stuff. Each item in the array has another array payroll_run_items
inside. I would like to get the sum of amount
of all items in that sub-array within my map method. Is this even possible within map (s.th. like creating a map inside a map)? I could only make it happen via looping and calculating the value beforehand outside the map method.
payrollRuns object:
(23) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0:
amount: "0.00"
company: {id: 1, name: 'Example Ltd.', country: 'Germany', city: 'Munich', zip: '80801', …}
line_items: 0
month: {id: 55, period: '2024-03-01'}
payroll_run_items: Array(4)
0: {id: 338, amount: '3780.00', offer: {…}, month: {…}, payroll_run: {…}}
1: {id: 361, amount: '4428.28', offer: {…}, month: {…}, payroll_run: {…}}
2: {id: 384, amount: '3780.00', offer: {…}, month: {…}, payroll_run: {…}}
3: {id: 407, amount: '3780.00', offer: {…}, month: {…}, payroll_run: {…}}
const PayrollRuns = (props) => {
const runItems = props.payrollRuns.map((run) =>
<div key={run.id} className="flex p-4 text-lg">
..
<div>{sum of all amounts of payroll_run_items array..}</div>
</div>
);
return (
<div className="runs-wrapper bg-white rounded-xl h-full w-48 shadow-sx-shadow p-4 flex flex-col">
<h1 className="border-b-2 pb-4">Payroll Runs</h1>
<div className="grow overflow-auto">{runItems}</div>
</div>
)
}
export default PayrollRuns
CodePudding user response:
Yes, you need to use reduce:
const runItems = props.payrollRuns.map((run) =>
<div key={run.id} className="flex p-4 text-lg">
..
<div>{run.payroll_run_items.reduce((acc, value) => {
return acc.amount value.amount;
})}</div>
</div>
);