You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

Step 1: Build a Reusable Conversion Function

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';
};
Step 2: Use the Function in Your App Logic

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'
Step 3: Optional - Add Reverse Mapping (For API Submissions)

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
Step 4: Bonus Enhancements
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:32:20