-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathFlatten_object.js
58 lines (48 loc) · 1.03 KB
/
Flatten_object.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
// Given a deeply nested object,create a function on the object that returns the flat version of the original object.
/*
Input:
let obj = {
Company: "google",
Address: "san francisco",
contact: +91-999999999,
office: {
office1: "gurugram",
office2: "bengaluru",
office3: ["hyderabad,mumbai"]
}
};
Output:
{
Address: "san francisco",
Company: "google",
contact: -999999908,
office.office1: "gurugram",
office.office2: "bengaluru",
office.office3: ["hyderabad,mumbai"]
}
*/
let obj = {
Company: "google",
Address: "san francisco",
contact: +91 - 999999999,
office: {
office1: "gurugram",
office2: "bengaluru",
office3: ["hyderabad,mumbai"],
},
};
const flattenObj = (ob) => {
let result = {};
for (const i in ob) {
if (typeof ob[i] === "object" && !Array.isArray(ob[i])) {
const temp = flattenObj(ob[i]);
for (const j in temp) {
result[i + "." + j] = temp[j];
}
} else {
result[i] = ob[i];
}
}
return result;
};
console.log(flattenObj(obj));