-
-
Notifications
You must be signed in to change notification settings - Fork 768
/
Copy pathflattenPayload.ts
38 lines (36 loc) · 1.32 KB
/
flattenPayload.ts
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
export const flattenPayload = (
payload: Record<string, unknown> = {},
parentKey = '',
): Record<string, unknown> =>
Object.entries(payload).reduce(
(acc, [key, value]) => {
const newKey = parentKey ? `${parentKey}.${key}` : key;
if (
typeof value === 'object' &&
value !== null &&
!Array.isArray(value)
) {
// If it's an object, recurse and merge the results
Object.assign(
acc,
flattenPayload(value as Record<string, unknown>, newKey),
);
} else if (Array.isArray(value)) {
// If it's an array, map through it and handle objects and non-objects differently
value.forEach((item, index) => {
if (typeof item === 'object' && item !== null) {
Object.assign(
acc,
flattenPayload(item, `${newKey}[${index}]`),
);
} else {
acc[`${newKey}[${index}]`] = item;
}
});
} else {
acc[newKey] = value;
}
return acc;
},
{} as Record<string, unknown>,
);