-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathfhir.ts
More file actions
42 lines (32 loc) · 1.29 KB
/
fhir.ts
File metadata and controls
42 lines (32 loc) · 1.29 KB
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
function isEmptyObject(data: any) {
return typeof data === 'object' && !Array.isArray(data) && data !== null && Object.keys(data).length === 0;
}
export function cleanObject(data: any, topLevel = true): any {
if (Array.isArray(data)) {
const cleanedArray = data.map((item) => {
const cleaned = cleanObject(item, false);
//NOTE: convert undefined → null
return cleaned === undefined ? null : cleaned;
});
//NOTE: Trim trailing nulls
while (cleanedArray.length > 0 && cleanedArray[cleanedArray.length - 1] === null) {
cleanedArray.pop();
}
return cleanedArray.length > 0 ? cleanedArray : undefined;
}
if (typeof data === 'object' && data !== null) {
const result: Record<string, any> = {};
for (const [key, value] of Object.entries(data)) {
const cleanedValue = cleanObject(value, false);
if (cleanedValue !== undefined && cleanedValue !== null && !isEmptyObject(cleanedValue)) {
result[key] = cleanedValue;
}
}
const isEmptyResult = Object.keys(result).length === 0;
if (topLevel && isEmptyResult) {
return {};
}
return isEmptyResult ? undefined : result;
}
return data;
}