-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflatten_map.js
More file actions
52 lines (48 loc) · 938 Bytes
/
Copy pathflatten_map.js
File metadata and controls
52 lines (48 loc) · 938 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
43
44
45
46
47
48
49
50
51
52
const sampleData1 = {
name: "sam",
age: 24,
characteristics: {
height: "6 feet",
complexion: "dark",
hair: "black",
},
techStack: {
language: "Javascript",
framework: {
name: "React",
version: "18",
},
},
};
const sampleData2 = {
a: {
b: {
c: 12,
d: "Hello World",
},
e: [1, 2, 3],
},
f: null,
};
const flattenObj = (obj) => {
const result = {};
for (const i in obj) {
//Check type of element is object and not an array
if (
obj[i] != null && // value of key not null
typeof obj[i] === "object" && // type is object
!Array.isArray(obj[i]) // Not an array
) {
const temp = flattenObj(obj[i]);
for (const j in temp) {
result[i + "." + j] = temp[j];
}
} else {
//Not and object
result[i] = obj[i];
}
}
return result;
};
const out = flattenObj(sampleData1);
console.log(out);