JAVASCRIPT

Transform API Response Data for Frontend Display

Learn effective techniques to reshape and adapt raw API response data into a clean, consistent format tailored for direct consumption by your frontend UI components.

/**
 * Transforms a raw API product response into a UI-friendly format.
 * @param {object} apiProduct - The product object received from the API.
 * @returns {object} - The transformed product object for UI display.
 */
function transformProductForUI(apiProduct) {
  if (!apiProduct) {
    return null;
  }

  // Example API product structure:
  // {
  //   "id_numeric": 12345,
  //   "product_name_long": "Awesome Gadget Pro 2000",
  //   "price_cents": 19999,
  //   "in_stock_boolean": true,
  //   "manufacturer_details": {
  //     "id": "manu1",
  //     "name": "Tech Corp."
  //   },
  //   "category_id": "CAT001"
  // }

  return {
    id: apiProduct.id_numeric,
    name: apiProduct.product_name_long,
    price: (apiProduct.price_cents / 100).toFixed(2), // Convert cents to dollars and format
    isAvailable: apiProduct.in_stock_boolean,
    supplier: apiProduct.manufacturer_details ? apiProduct.manufacturer_details.name : 'N/A',
    category: apiProduct.category_id, // Could also map to a human-readable name here
    imageUrl: apiProduct.main_image_url || '/placeholder.png' // Provide a default if missing
  };
}

/**
 * Transforms an array of API products.
 * @param {Array<object>} apiProducts - Array of product objects from the API.
 * @returns {Array<object>} - Array of transformed product objects.
 */
function transformProductListForUI(apiProducts) {
  if (!Array.isArray(apiProducts)) {
    console.warn("Expected an array for transformProductListForUI, received:", apiProducts);
    return [];
  }
  return apiProducts.map(transformProductForUI).filter(Boolean); // Filter out any nulls if transformProductForUI returns null for bad input
}

// Example Usage:
const rawApiResponse = [
  {
    "id_numeric": 101,
    "product_name_long": "Super Widget Alpha",
    "price_cents": 2550,
    "in_stock_boolean": true,
    "manufacturer_details": { "id": "mf1", "name": "Global Inc." }
  },
  {
    "id_numeric": 102,
    "product_name_long": "Mega Device Beta",
    "price_cents": 12000,
    "in_stock_boolean": false,
    "manufacturer_details": { "id": "mf2", "name": "Innovate Ltd." }
  },
  {
    "id_numeric": 103,
    "product_name_long": "Basic Gizmo Gamma",
    "price_cents": 500,
    "in_stock_boolean": true,
    "manufacturer_details": null // Example of missing data
  }
];

const uiProducts = transformProductListForUI(rawApiResponse);
console.log(JSON.stringify(uiProducts, null, 2));

/* Expected Output:
[
  {
    "id": 101,
    "name": "Super Widget Alpha",
    "price": "25.50",
    "isAvailable": true,
    "supplier": "Global Inc.",
    "category": undefined,
    "imageUrl": "/placeholder.png"
  },
  {
    "id": 102,
    "name": "Mega Device Beta",
    "price": "120.00",
    "isAvailable": false,
    "supplier": "Innovate Ltd.",
    "category": undefined,
    "imageUrl": "/placeholder.png"
  },
  {
    "id": 103,
    "name": "Basic Gizmo Gamma",
    "price": "5.00",
    "isAvailable": true,
    "supplier": "N/A",
    "category": undefined,
    "imageUrl": "/placeholder.png"
  }
]
*/
How it works: This JavaScript snippet provides a clear pattern for transforming raw API response data into a more usable, consistent format for your frontend components. APIs often return data with different naming conventions, nested structures, or raw values (like prices in cents) that aren't ideal for direct UI display. This `transformProductForUI` function renames properties, performs data type conversions (e.g., cents to dollars), handles missing data with defaults, and flattens nested objects, ensuring your UI receives exactly the data shape it expects.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs