-
-
Save chinhvo/93cbb8b6d0f34b6998f79bebbc4225f4 to your computer and use it in GitHub Desktop.
Recursively add parent objects to each child (lodash)
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
import _ from 'lodash'; | |
/* | |
* Description: | |
* Add `.parent` property (with reference to parent object) | |
* to each array item recursively. | |
* | |
* INPUT: | |
* | |
* parents [] | |
* parent {} | |
* children [] | |
* item {} | |
* item {} | |
* children [] | |
* item {} | |
* ... | |
* item: Object | |
* ... | |
*/ | |
function addParentRecursive(items) { | |
_(items).forEach(function(item) { | |
_(item.children).forEach(function(child) { | |
child.parent = item; | |
}) | |
addParentRecursive(item.children); | |
}); | |
return items; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment