Last active
May 27, 2016 00:41
-
-
Save coopermaruyama/8716d2bfcfbfb7a2a340e085d1d7207b to your computer and use it in GitHub Desktop.
ES6: Recursive vertical reducer
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
// | |
// * 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