-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeepFlatten_improved.js
More file actions
42 lines (39 loc) · 1013 Bytes
/
deepFlatten_improved.js
File metadata and controls
42 lines (39 loc) · 1013 Bytes
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
const obj = {
A: "12",
B: 23,
C: {
P: 23,
O: {
L: 56,
},
Q: [1, 2],
},
D: null,
E: {},
F: [],
};
// Your original version for comparison
let flattenObj = {};
const flatteningObj = (obj, parent) => {
const keys = Object.keys(obj);
keys.forEach((key) => {
const value = obj[key];
const newParent = parent ? `${parent}.${key}` : key;
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
flatteningObj(obj[key], newParent);
} else if (Array.isArray(value)) {
value.forEach((item, index) => {
const arrayKey = `${newParent}.${index}`;
if (typeof item === "object" && item !== null && !Array.isArray(item)) {
flatteningObj({ [index]: item }, newParent);
} else {
flattenObj = { ...flattenObj, [arrayKey]: item };
}
});
} else {
flattenObj = { ...flattenObj, [newParent]: value };
}
});
};
flatteningObj(obj);
console.log("Your version:", flattenObj);