Last active
June 14, 2024 02:56
-
-
Save andymerskin/e6c8bae4c89411304404 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