Skip to content

Instantly share code, notes, and snippets.

@Palisand
Created December 16, 2017 17:47
Show Gist options
  • Save Palisand/e9fd237ec606229d7b095647f7a5cbdb to your computer and use it in GitHub Desktop.
Save Palisand/e9fd237ec606229d7b095647f7a5cbdb to your computer and use it in GitHub Desktop.
Mutate object list values to object with values holding property paths
/**
* 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