我有一個物件,我在 React 組件中映射來渲染一些東西。陣列中的每個專案內部都有另一個陣列payroll_run_items
。我想amount
在我的 map 方法中獲取該子陣列中所有專案的總和。這在地圖中是否可能(例如在地圖中創建地圖)?我只能通過在 map 方法之外預先回圈和計算值來實作它。
payrollRuns 物件:
(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
uj5u.com熱心網友回復:
是的,你需要使用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>
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/468498.html
標籤:javascript 反应