-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobjectFlatten.js
61 lines (52 loc) · 1.31 KB
/
objectFlatten.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
function flattenObject (nestedObject = {}) {
const flatObject = {}
// For each path through object, we will build a keyString.
// For each leaf, we will output the keyString.
// I don't know how many leaves until I find them all.
// Therefore traverse it and find all the leaves.
// Build a breadcrumb trail going forward.
// This recursive function doesn't return anything.
// At leaf case it mutates an object in outer scope.
function traverseObject (subTree = {}, breadcrumb = []) {
Object.keys(subTree).forEach(key => {
const nextBreadcrumb = key ? breadcrumb.concat(key) : breadcrumb
const value = subTree[key]
if (typeof value === 'object' && value !== null) {
traverseObject(value, nextBreadcrumb)
} else {
const keyString = nextBreadcrumb.join('.')
flatObject[keyString] = value
}
})
}
traverseObject(nestedObject)
return flatObject
}
const user = {
id: 101,
email: '[email protected]',
personalInfo: {
name: 'Jack',
address: {
line1: 'westwish st',
line2: 'washmasher',
city: 'wallas',
state: 'WX'
}
}
}
const dict = {
Key1: '1',
Key2: {
a: '2',
b: '3',
c: {
d: '3',
e: {
'': '1'
}
}
}
}
console.log(flattenObject(user))
console.log(flattenObject(dict))