JavaScript中API枚举值转应用字符串的实现咨询
Nice job setting up your mapping object — that's the perfect foundation! Let's walk through how to use this to convert those API numeric values into the string labels your app needs, plus some handy extras:
First, add a helper function to your comparisonFactor.js file that handles the conversion, including edge cases like undefined values or unexpected numeric inputs:
// comparisonFactor.js export const comparisonTypes = { 0: 'PerKilogram', 1: 'PerLitre', 2: 'PerPiece', 3: 'PerMetre', 4: 'PerLoad', 5: 'PerWash', 6: 'ReadyToDrink', 7: 'ReadyToEat', 8: 'DrainedWeight', }; // Helper to convert API numeric value to app string export const getComparisonTypeLabel = (value) => { // Fallback to a default label if the value isn't in our mapping return comparisonTypes[value] || 'UnknownComparisonType'; };
When you receive data from the API, call this helper to translate the numeric comparisonFactor into your app's string representation:
// Example: In a component or data service import { getComparisonTypeLabel } from './comparisonFactor'; // Assume this is your parsed API response const apiData = { price: { currentPrice: { comparisonFactor: 1 } } }; // Convert the value for display or storage const displayLabel = getComparisonTypeLabel(apiData.price.currentPrice.comparisonFactor); console.log(displayLabel); // Outputs: 'PerLitre'
If you ever need to convert your app's string labels back to numeric values (e.g., when sending data to the API via a form), add a reverse mapping:
// In comparisonFactor.js export const comparisonTypeValues = Object.fromEntries( Object.entries(comparisonTypes).map(([key, value]) => [value, parseInt(key)]) ); // Usage example: Convert string back to number const numericValue = comparisonTypeValues['PerKilogram']; console.log(numericValue); // Outputs: 0
- Prevent accidental mapping changes: Freeze your mapping object to stop it from being modified elsewhere in the app:
export const comparisonTypes = Object.freeze({ // ... your existing key-value pairs }); - Type safety (if using TypeScript): If your project uses TS, you can enforce valid values with enums and typed functions:
// comparisonFactor.ts export enum ComparisonType { PerKilogram = 0, PerLitre = 1, PerPiece = 2, // ... rest of your values } export const comparisonTypeLabels: Record<ComparisonType, string> = { [ComparisonType.PerKilogram]: 'PerKilogram', [ComparisonType.PerLitre]: 'PerLitre', // ... match your original mapping }; export const getComparisonTypeLabel = (value: ComparisonType): string => { return comparisonTypeLabels[value] || 'UnknownComparisonType'; };
内容的提问来源于stack exchange,提问作者Joelgullander

