Skip to content

Instantly share code, notes, and snippets.

@andymerskin
Last active June 14, 2024 02:56
Show Gist options
  • Save andymerskin/e6c8bae4c89411304404 to your computer and use it in GitHub Desktop.
Save andymerskin/e6c8bae4c89411304404 to your computer and use it in GitHub Desktop.
Recursively add parent objects to each child (lodash)
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