JAVASCRIPT
Transform and Normalize API Response Data (JavaScript)
Learn to process raw API data in JavaScript, transforming it into a clean, normalized structure suitable for display or further application logic.
/**
* Transforms a raw API user response into a normalized format for the frontend.
* @param {object[]} rawUsers - An array of user objects from the API.
* @returns {object[]} An array of normalized user objects.
*/
function normalizeUserData(rawUsers) {
if (!Array.isArray(rawUsers)) {
console.error("Expected an array for rawUsers, received:", rawUsers);
return [];
}
return rawUsers.map(user => {
// Handle potential missing fields and rename/restructure
const firstName = user.name?.first || 'N/A';
const lastName = user.name?.last || 'N/A';
const email = user.contact?.email_address || 'No Email';
const userId = user._id || user.id || null; // API might use different ID keys
const isActive = user.status === 'active'; // Transform status to boolean
return {
id: userId,
fullName: `${firstName} ${lastName}`,
emailAddress: email,
joinedDate: user.registrationDate ? new Date(user.registrationDate).toLocaleDateString() : 'Unknown',
profilePicture: user.profile_img_url || '/default-avatar.png',
isActiveUser: isActive,
// You might exclude sensitive or unnecessary fields here
// e.g., if (user.internal_id) { normalizedUser.internalId = user.internal_id; }
};
}).filter(user => user.id !== null); // Filter out entries without a valid ID
}
// Example raw API response
// const apiResponse = [
// {
// "_id": "6543210abcdef",
// "name": { "first": "Jane", "last": "Doe" },
// "contact": { "email_address": "[email protected]", "phone": "123-456-7890" },
// "registrationDate": "2022-01-15T10:30:00Z",
// "status": "active",
// "profile_img_url": "https://example.com/jane.jpg",
// "internal_secret": "xyz123"
// },
// {
// "id": "abc0987654321",
// "name": { "first": "John", "last": "Smith" },
// "contact": { "email_address": "[email protected]" },
// "registrationDate": "2023-03-20T14:00:00Z",
// "status": "inactive"
// }
// ];
// const normalizedUsers = normalizeUserData(apiResponse);
// console.log(normalizedUsers);
/*
[
{
id: '6543210abcdef',
fullName: 'Jane Doe',
emailAddress: '[email protected]',
joinedDate: '1/15/2022',
profilePicture: 'https://example.com/jane.jpg',
isActiveUser: true
},
{
id: 'abc0987654321',
fullName: 'John Smith',
emailAddress: '[email protected]',
joinedDate: '3/20/2023',
profilePicture: '/default-avatar.png',
isActiveUser: false
}
]
*/
How it works: This JavaScript function demonstrates how to transform and normalize data received from an API. It maps over an array of raw user objects, restructuring them to a more consistent and user-friendly format for the frontend. This includes renaming keys, combining fields (like first and last name), handling missing data with defaults, converting data types (e.g., status string to boolean), and standardizing date formats. This practice ensures your UI components receive predictable data, regardless of the API's original structure.