-
Notifications
You must be signed in to change notification settings - Fork 0
/
flattenObject.js
62 lines (57 loc) · 1.48 KB
/
flattenObject.js
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
53
54
55
56
57
58
59
60
61
62
const obj = {
skills: ["javaScript", "python", "react", "node"],
name: {
first: "aditya",
last: "suman"
},
age: 23,
college: {
name: "IIT Patna",
address: {
city: "bihta",
district: "patna",
pin: 801101,
locs: {
lang: "123.1.2",
lat: 90
}
},
courses: ["CSE", "EE", "ME", "CHE", "CE", "MTE", "DS"]
},
projects: [
{
name: "project 1",
details: {
desc: "project 1 is magic",
link: "https://example.com/project1",
tech: ["node", "js", "react"]
}
},
{
name: "project 2",
details: {
desc: "project 2 is awesome",
link: "https://example.com/project2",
tech: ["python", "java", "html"]
}
}
]
};
function flattenObj(obj, parentKey = "") {
let newObj = {};
function flattenObjUtil(obj, parentKey = "") {
Object.keys(obj).forEach(key => {
const val = obj[key];
const newKey = (parentKey ? parentKey + "_" : "") + key;
if (typeof val === "object") {
flattenObjUtil(val, newKey)
} else {
newObj[newKey] = val;
}
});
}
flattenObjUtil(obj, parentKey);
return newObj;
}
const ans = flattenObj(obj);
console.log("flatten obj", ans)