Skip to content

Instantly share code, notes, and snippets.

@chinhvo
Forked from andymerskin/recursive_parents.js
Created June 14, 2024 02:56
Show Gist options
  • Save chinhvo/93cbb8b6d0f34b6998f79bebbc4225f4 to your computer and use it in GitHub Desktop.
Save chinhvo/93cbb8b6d0f34b6998f79bebbc4225f4 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