forked from swaranrajlaxmi/javascript-coding-practice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflattenObject.js
More file actions
43 lines (39 loc) · 893 Bytes
/
flattenObject.js
File metadata and controls
43 lines (39 loc) · 893 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
let obj = {
"a": {
"b": {
"c": 12,
"d": "Hello World",
"e": null
},
"f": [1,2,3]
}
};
const flatten = (obj, parentkey) => {
return Object.keys(obj).reduce((acc, key) => {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
let val = obj[key];
if (typeof val === "object" && !Array.isArray(val) && val != null) { // != will catch undefined or null
let flat = flatten(val, key);
if (parentkey) {
for (let i in flat) {
let k = `${parentkey}/${i}`;
acc[k] = flat[i];
}
} else {
acc = flat;
}
} else {
let prop = parentkey ? `${parentkey}/${key}` : key;
acc[prop] = val;
}
}
return acc;
}, {});
};
console.log(flatten(obj));
// {
// a/b/c: 12,
// a/b/d: "Hello World",
// a/b/e: null,
// a/f: [1, 2, 3]
// }