Angular中如何对状态为settled的claimed_value数组值求和
Solution to Sum
claimed_value for Settled Claims Hey there! I see you're already fetching your claims data and counting settled/submitted records—great start! To sum up the claimed_value for all entries with status: 'settled', you can use JavaScript's reduce() method right alongside your existing logic. Here's how to update your code:
Modified Code
getClaims(){ let url; if(this.userFilter.company_id){ url = 'http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-api/get_claims.php?company_id='+this.userFilter.company_id; }else{ url = 'http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-api/get_claims.php?offset=0&limit=200'; } this.clientData = this.httpClient.get(url).subscribe(data => { console.log(data); this.data = data.records; const statusSettled = 'settled'; const statusSubmitted = 'submitted'; // Count settled records const countsettled = this.data.filter((obj) => obj.status === statusSettled).length; this.countsettled = countsettled; console.log(countsettled); // Count submitted records const countunsettled = this.data.filter((obj) => obj.status === statusSubmitted).length; this.countunsettled = countunsettled; console.log(countunsettled); // Calculate total claimed value for settled claims const totalSettledClaimedValue = this.data.reduce((total, claim) => { // Ensure status is settled and claimed_value is a valid number if (claim.status === statusSettled) { // Parse to number in case claimed_value is a string from the API const value = parseFloat(claim.claimed_value); return total + (isNaN(value) ? 0 : value); } return total; }, 0); // Start with a total of 0 console.log('Total Settled Claimed Value:', totalSettledClaimedValue); this.totalSettledClaimedValue = totalSettledClaimedValue; // Store in component property }); }
Key Changes Explained
- Used
reduce()for summation: This method iterates over yourdataarray, accumulates the sum only for records wherestatusis 'settled'. - Handled string values: Added
parseFloat()to convertclaimed_valueto a number (in case it comes as a string from the API) andisNaN()to skip invalid values that can't be converted. - Cleaned up variable names: Renamed vague
statusandstatus2to descriptivestatusSettledandstatusSubmittedfor better readability. - Moved
urldeclaration outside the if/else: Avoided redeclaringlet urltwice to keep the code cleaner.
Alternative Approach (Filter First, Then Reduce)
If you prefer a more explicit, step-by-step flow, you can filter the settled records first, then sum their values:
const settledClaims = this.data.filter(obj => obj.status === statusSettled); const totalSettledClaimedValue = settledClaims.reduce((total, claim) => { const value = parseFloat(claim.claimed_value); return total + (isNaN(value) ? 0 : value); }, 0);
This does the exact same calculation—just splits the logic into two clear steps, which might be easier to follow for some.
内容的提问来源于stack exchange,提问作者Umaiz Khan
相关产品推荐
相关产品推荐

