JAVASCRIPT

Normalize Complex API Responses for UI Consumption

Learn to transform raw, nested API data into a flat, consistent, and easily consumable format, simplifying state management and rendering in your JavaScript frontend.

/**
 * Normalizes a complex API response into a flatter, more consistent structure.
 * This example transforms a list of users with nested address/company details
 * into a unified user object.
 * @param {Array<Object>} apiResponse - The raw API response array of user objects.
 * @returns {Array<Object>} An array of normalized user objects.
 */
function normalizeUsersApiResponse(apiResponse) {
    if (!Array.isArray(apiResponse)) {
        console.warn("Expected an array for API response, got:", apiResponse);
        return [];
    }

    return apiResponse.map(user => ({
        id: user.id,
        name: user.name,
        email: user.email,
        phone: user.phone,
        website: user.website,
        // Flatten address details
        addressStreet: user.address?.street,
        addressSuite: user.address?.suite,
        addressCity: user.address?.city,
        addressZipcode: user.address?.zipcode,
        // Flatten company details
        companyName: user.company?.name,
        companyCatchPhrase: user.company?.catchPhrase,
        companyBs: user.company?.bs
    }));
}

// --- Usage Example ---
const rawApiResponse = [
    {
        "id": 1,
        "name": "Leanne Graham",
        "username": "Bret",
        "email": "[email protected]",
        "address": {
            "street": "Kulas Light",
            "suite": "Apt. 556",
            "city": "Gwenborough",
            "zipcode": "92998-3874",
            "geo": { "lat": "-37.3159", "lng": "81.1496" }
        },
        "phone": "1-770-736-8031 x56442",
        "website": "hildegard.org",
        "company": {
            "name": "Romaguera-Crona",
            "catchPhrase": "Multi-layered client-server neural-net",
            "bs": "harness real-time e-markets"
        }
    },
    {
        "id": 2,
        "name": "Ervin Howell",
        "username": "Antonette",
        "email": "[email protected]",
        "address": {
            "street": "Victor Plains",
            "suite": "Suite 879",
            "city": "Wisokyburgh",
            "zipcode": "90566-7771",
            "geo": { "lat": "-43.9509", "lng": "-34.4618" }
        },
        "phone": "010-692-6593 x09125",
        "website": "anastasia.net",
        "company": {
            "name": "Deckow-Crist",
            "catchPhrase": "Proactive didactic contingency",
            "bs": "synergize scalable supply-chains"
        }
    }
];

const normalizedUsers = normalizeUsersApiResponse(rawApiResponse);
console.log(JSON.stringify(normalizedUsers, null, 2));
/*
Expected output structure for a single user:
{
    "id": 1,
    "name": "Leanne Graham",
    "email": "[email protected]",
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "addressStreet": "Kulas Light",
    "addressSuite": "Apt. 556",
    "addressCity": "Gwenborough",
    "addressZipcode": "92998-3874",
    "companyName": "Romaguera-Crona",
    "companyCatchPhrase": "Multi-layered client-server neural-net",
    "companyBs": "harness real-time e-markets"
}
*/
How it works: This JavaScript snippet demonstrates how to normalize a complex, potentially deeply nested API response. The `normalizeUsersApiResponse` function iterates over an array of user objects, flattening nested `address` and `company` fields into top-level properties. This transformation creates a more consistent and predictable data structure, simplifying data access, state management, and rendering logic in your frontend application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs