Created
December 16, 2017 17:47
-
-
Save Palisand/e9fd237ec606229d7b095647f7a5cbdb to your computer and use it in GitHub Desktop.
Mutate object list values to object with values holding property paths
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
/** | |
* Convert | |
* | |
* foo: { | |
* bar: ['baz', 'qux'], | |
* } | |
* | |
* to | |
* | |
* foo: { | |
* bar: { | |
* baz: 'bar/baz/', | |
* qux: 'bar/qux/', | |
* } | |
* } | |
*/ | |
function setPaths(obj, path = '', level = 0) { | |
return Object.keys(obj).reduce((branches, key) => | |
!Array.isArray(obj[key]) ? | |
{...branches, [key]: setPaths( | |
obj[key], | |
level === 0 ? path : (level === 1 ? key : [path, key].join('/')), | |
level + 1 | |
)} : | |
{...branches, [key]: { | |
...branches[key], | |
...obj[key].reduce((leaves, leaf) => ({ | |
...leaves, [leaf]: [...path ? [path] : [], key, leaf].join('/') + '/', | |
}), {}), | |
}} | |
, {} | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment