forked from priya42bagde/JavaScript-with-JC
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlatten-Object.js
More file actions
54 lines (49 loc) · 1.23 KB
/
Copy pathFlatten-Object.js
File metadata and controls
54 lines (49 loc) · 1.23 KB
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
/* 💡"JavaScript-with-JC"
👉 Flatten Object implementation */
const person = {
name: "Jayesh",
address: {
state: "M.P",
country: "India",
subAdress: {
city: "Burhanpur",
},
},
skills: {
frontend: ["JavaScript", "React Js", "CSS"],
backend: ["Node Js", "Mongo Db"],
},
};
const flattenObject = (obj) => {
const result = {};
//// looping through obj
for (let key in obj) {
// checking type of key
if (typeof obj[key] === "object") {
// if object call flattenObject again
const temp = flattenObject(obj[key]);
for (let childKey in temp) {
// concatenate key with childKey => key.childKey
result[key + "." + childKey] = temp[childKey];
}
} else {
// else store obj[key] in result directly
result[key] = obj[key];
}
}
return result;
};
const flattenPerson = flattenObject(person);
console.log(flattenPerson);
// output
// {
// name: "Jayesh",
// address.state: "M.P",
// address.country: "India",
// address.subAdress.city: "Burhanpur",
// skills.frontend.0: "JavaScript",
// skills.frontend.1: "React Js",
// skills.frontend.2: "CSS",
// skills.backend.0: "Node Js",
// skills.backend.1: "Mongo Db"
// }