Skip to content

Instantly share code, notes, and snippets.

@coopermaruyama
Last active May 27, 2016 00:41
Show Gist options
  • Save coopermaruyama/8716d2bfcfbfb7a2a340e085d1d7207b to your computer and use it in GitHub Desktop.
Save coopermaruyama/8716d2bfcfbfb7a2a340e085d1d7207b to your computer and use it in GitHub Desktop.
ES6: Recursive vertical reducer
//
// * Given some data that looks like this:
//
// let data = [
// {
// key: 'a',
// value: 'a1',
// children: [
// {
// key: 'b',
// value: 'b1',
// children: [{ key: 'c', value: 'c1' }, { key: 'c', value: 'c2' }]
// },
// {
// key: 'b',
// value: 'b2',
// children: [{ key: 'c', value: 'c3' }, { key: 'c', value: 'c4' }]
// }
// ]
// },
// {
// key: 'a',
// value: 'a2',
// children: [
// {
// key: 'b',
// value: 'b3',
// children: [{ key: 'c', value: 'c5' }, { key: 'c', value: 'c6' }]
// },
// {
// key: 'b',
// value: 'b4',
// children: [{ key: 'c', value: 'c7' }, { key: 'c', value: 'c8' }]
// }
// ]
// }
// ];
//
// * mergeChildren(data) returns this:
//
// {
// a: [
// { value: "a1" },
// { value: "a2" }
// ],
// b: [
// { value: "b1" },
// { value: "b2" },
// { value: "b3" },
// { value: "b4" }
// ],
// c: [
// { value: "c1" },
// { value: "c2" },
// { value: "c3" },
// { value: "c4" },
// { value: "c5" },
// { value: "c6" },
// { value: "c7" },
// { value: "c8" }
// ]
// }
const mergeChildren = (children, prev) => {
return children.reduce((p,c) => {
const prev = p[c.key] || [];
const merged = { ...p, [c.key]: [ ...prev, { value: c.value }]};
return c.children ? mergeChildren(c.children, merged) : merged;
}, prev || {})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment