Last active
April 21, 2020 07:27
-
-
Save rafaelkendrik/a8607d5638e635f9b2e286816675efb7 to your computer and use it in GitHub Desktop.
Walking through a tree, combining reduce and recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const tree = { | |
obj1: { | |
obj2: { | |
key1: 'key1' | |
}, | |
obj3: { | |
obj4: { | |
key2: 'key2' | |
} | |
} | |
}, | |
obj5: { | |
key3: 'key3' | |
} | |
} | |
const replacePattern = val => ({ value: val }) | |
const replaceTree = obj => | |
Object | |
.entries(obj) | |
.reduce((acc, [key, val]) => { | |
acc[key] = (val === Object(val)) | |
? replaceTree(val) | |
: replacePattern(val) | |
return acc | |
}, {}) | |
const newTree = replaceTree(tree) | |
console.log(newTree) // { obj1: { obj2: { key1: [Object] }, obj3: { obj4: [Object] } }, obj5: { key3: { value: 'key3' } } } | |
console.log(newTree.obj1.obj2.key1) // { value: 'key1' } | |
console.log(newTree.obj1.obj3.obj4.key2) // { value: 'key2' } | |
console.log(newTree.obj5.key3) // { value: 'key3' } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment