Skip to content

Commit 60f0de2

Browse files
committed
added flatten object silution
1 parent b2447bd commit 60f0de2

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

EventLoopOutput.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
let a = true;
66
let count = 0;
77

8-
setTimeout(() => {
8+
setTimeout(() => {
99
a = false;
1010
}, 2000);
1111

Flatten_object.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Given a deeply nested object,create a function on the object that returns the flat version of the original object.
2+
/*
3+
Input:
4+
5+
let obj = {
6+
Company: "google",
7+
Address: "san francisco",
8+
contact: +91-999999999,
9+
office: {
10+
office1: "gurugram",
11+
office2: "bengaluru",
12+
office3: ["hyderabad,mumbai"]
13+
}
14+
};
15+
16+
Output:
17+
{
18+
Address: "san francisco",
19+
Company: "google",
20+
contact: -999999908,
21+
office.office1: "gurugram",
22+
office.office2: "bengaluru",
23+
office.office3: ["hyderabad,mumbai"]
24+
}
25+
26+
*/
27+
28+
let obj = {
29+
Company: "google",
30+
Address: "san francisco",
31+
contact: +91 - 999999999,
32+
office: {
33+
office1: "gurugram",
34+
office2: "bengaluru",
35+
office3: ["hyderabad,mumbai"],
36+
},
37+
};
38+
39+
const flattenObj = (ob) => {
40+
let result = {};
41+
42+
for (const i in ob) {
43+
if (typeof ob[i] === "object" && !Array.isArray(ob[i])) {
44+
const temp = flattenObj(ob[i]);
45+
for (const j in temp) {
46+
result[i + "." + j] = temp[j];
47+
}
48+
} else {
49+
result[i] = ob[i];
50+
}
51+
}
52+
return result;
53+
};
54+
55+
console.log(flattenObj(obj));

0 commit comments

Comments
 (0)