React数组映射时条件仅首次生效:如何为指定表格字段添加美元符号
Hey there, I see the issue you're facing—you want to prepend a dollar sign to multiple numeric fields (gross_sales, discounts, tax, net_sales) in your React table, but right now only gross_sales is getting it. Let's break down what's wrong and fix it quickly.
What's Causing the Problem?
Your conditional check has a common logical error:
item === ('gross_sales' || 'discounts' || 'tax' || 'net_sales' || 'average_amount' || 'total_spent')
The || operator here returns the first "truthy" value in the sequence, which is always 'gross_sales'. So your condition simplifies to item === 'gross_sales'—that's why only that field works.
The Fix
Instead of using ||, create an array of fields that need the dollar sign, then check if the current item is in that array using Array.includes(). Here's how to adjust your code:
First, define the list of fields that should show the dollar sign:
const tableHeadings = ["month", "orders", "gross_sales", "discounts", "tax", "net_sales"]; const reportData = [ { "orders": 119, "gross_sales": 21819.610000000008, "net_sales": 21819.610000000008, "discounts": 865.82, "tax": 0, "month": "October 2021" }, { "orders": 7, "gross_sales": 4542.4, "net_sales": 4542.4, "discounts": 40, "tax": 0, "month": "September 2021" } ]; // Define fields that need dollar formatting const dollarFields = ['gross_sales', 'discounts', 'tax', 'net_sales', 'average_amount', 'total_spent'];
Then update your table rendering code:
<tbody> {reportData.length > 0 && tableHeadings.length > 0 && reportData.map((element, index) => ( <tr key={index}> {tableHeadings.map((item, idx) => ( <td key={idx}> {/* Check if current field is in our dollarFields array */} {dollarFields.includes(item) && '$'} {element[item]} </td> ))} </tr> ))} </tbody>
Bonus: Better Numeric Formatting (Optional)
If you want to clean up those long decimal values (like 21819.610000000008) and format them properly as currency, use the browser's built-in Intl.NumberFormat API instead of just adding a dollar sign:
<td key={idx}> {dollarFields.includes(item) ? new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(element[item]) : element[item] } </td>
This will automatically format numbers to $21,819.61 and $4,542.40, which looks much cleaner for financial data.
内容的提问来源于stack exchange,提问作者Jeesmon Joy

