Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 6985b1a

Browse files
committedApr 25, 2025
refactor: improve object flatten function
1 parent 5224088 commit 6985b1a

File tree

1 file changed

+32
-26
lines changed

1 file changed

+32
-26
lines changed
 

‎src/utils/flat.ts

Lines changed: 32 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -10,37 +10,43 @@ export function flattenObject(obj: any, prefix: string = ''): Record<string, any
1010
const flattened: Record<string, any> = {}
1111

1212
for (const key in obj) {
13-
if (Object.prototype.hasOwnProperty.call(obj, key)) {
14-
const value = obj[key]
15-
const newKey = prefix ? `${prefix}.${key}` : key
13+
if (!Object.prototype.hasOwnProperty.call(obj, key)) {
14+
continue
15+
}
1616

17-
if (value && typeof value === 'object' && !Array.isArray(value)) {
18-
// Handle nested objects
19-
Object.assign(flattened, flattenObject(value, newKey))
20-
} else if (Array.isArray(value)) {
21-
// Handle arrays
22-
const isPrimitiveArray = value.every(
23-
(item: any) => typeof item !== 'object' || item === null
24-
)
17+
const value = obj[key]
18+
const newKey = prefix ? `${prefix}.${key}` : key
2519

26-
if (isPrimitiveArray) {
27-
// Handle primitive arrays as single value
28-
flattened[newKey] = value
29-
} else {
30-
// Handle arrays containing objects
31-
value.forEach((item: any, index: number) => {
32-
if (item && typeof item === 'object' && !Array.isArray(item)) {
33-
Object.assign(flattened, flattenObject(item, `${newKey}[${index}]`))
34-
} else {
35-
flattened[`${newKey}[${index}]`] = item
36-
}
37-
})
38-
}
39-
} else {
40-
// Handle primitive values
20+
if (value && typeof value === 'object' && !Array.isArray(value)) {
21+
// Handle nested objects
22+
Object.assign(flattened, flattenObject(value, newKey))
23+
continue
24+
}
25+
26+
if (Array.isArray(value)) {
27+
// Handle arrays
28+
const isPrimitiveArray = value.every(
29+
(item: any) => typeof item !== 'object' || item === null
30+
)
31+
32+
if (isPrimitiveArray) {
33+
// Handle primitive arrays as single value
4134
flattened[newKey] = value
35+
} else {
36+
// Handle arrays containing objects
37+
value.forEach((item: any, index: number) => {
38+
if (item && typeof item === 'object' && !Array.isArray(item)) {
39+
Object.assign(flattened, flattenObject(item, `${newKey}[${index}]`))
40+
} else {
41+
flattened[`${newKey}[${index}]`] = item
42+
}
43+
})
4244
}
45+
continue
4346
}
47+
48+
// Handle primitive values
49+
flattened[newKey] = value
4450
}
4551

4652
return flattened

0 commit comments

Comments
 (0)
Please sign in to comment.