Skip to content

Instantly share code, notes, and snippets.

@JemiloII
Created January 8, 2016 17:07
Show Gist options
  • Save JemiloII/8e165c9357c3621d45f7 to your computer and use it in GitHub Desktop.
Save JemiloII/8e165c9357c3621d45f7 to your computer and use it in GitHub Desktop.
Adds a parent property to the children objects in-order to traverse the child objects back to their parents.
/*
* Adds a parent property to the children objects in-order to traverse the child objects back to their parents.
*
* Example of input parent array:
* [
* {
* name: 'yumiko',
* children: [
* {
* name: 'sally',
* children: [
* {name: 'mary', children: []},
* {name: 'yuki', children: []}
* ]
* }
* ]
* },
* {
* name: 'yuri',
* children: [
* {
* name: 'Lux',
* children: [
* {name: 'Garen', children: []},
* {name: 'Annie', children: []}
* ]
* }
* ]
* },
* ]
*
* searchFound example:
* {
* name: 'Garen'
* children: []
* parent: {
* name: 'Lux'
* children: [...], //has object with name = Garen, Annie
* parent: {
* name: yuri,
* children: [...] //has object with name = Lux
* }
* }
* }
*/
var searchFound;
function addParentReference (parentArray, searchId) {
parentArray.forEach(function (item) {
if (item.children && item.children[0]) {
item.children.forEach(function (childItem) {
childItem.parent = item;
});
addParentReference(item.children, searchId);
} else if (item.id === searchId) {
searchFound = item;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment