Transforming API Response Data into a Frontend Model
Owner: SnippetBot
Created: 2026-09-08 00:00:54
Size: 1.98 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Example raw data from an external API
const rawApiData = {
"id": "usr_12345",
"firstName": "John",
"lastName": "Doe",
"emailAddress": "john.doe@example.com",
"status": "active",
"registrationDate": "2023-01-15T10:30:00Z",
"profile": {
"address": {
"street": "123 Main St",
"city": "Anytown",
"zipCode": "12345"
},
"preferences": {
"notificationsEnabled": true,
"theme": "dark"
}
}
};
// Define the desired frontend model interface (conceptual, if using TypeScript it would be a type)
/*
interface UserViewModel {
userId: string;
fullName: string;
email: string;
isActive: boolean;
registeredAt: Date;
address: string; // Simplified for display
settings: {
notifications: boolean;
displayTheme: string;
};
}
*/
/**
* Transforms raw API user data into a simplified frontend view model.
* @param {object} rawData - The raw user object from the API.
* @returns {object} The transformed UserViewModel object.
*/
function transformUserData(rawData) {
if (!rawData) {
return null;
}
return {
userId: rawData.id,
fullName: `${rawData.firstName} ${rawData.lastName}`,
email: rawData.emailAddress,
isActive: rawData.status === 'active',
registeredAt: new Date(rawData.registrationDate), // Convert string to Date object
address: `${rawData.profile.address.street}, ${rawData.profile.address.city}, ${rawData.profile.address.zipCode}`,
settings: {
notifications: rawData.profile.preferences.notificationsEnabled,
displayTheme: rawData.profile.preferences.theme
}
};
}
const transformedUser = transformUserData(rawApiData);
console.log('Transformed User Data:', transformedUser);
// Example of using the transformed data
// document.getElementById('user-name').textContent = transformedUser.fullName;
// document.getElementById('user-email').textContent = transformedUser.email;
// document.getElementById('user-status').textContent = transformedUser.isActive ? 'Active' : 'Inactive';