Skip to content

Instantly share code, notes, and snippets.

@overclock11
Created August 22, 2018 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save overclock11/a7254623b6def0c593c96478bb52c959 to your computer and use it in GitHub Desktop.
Save overclock11/a7254623b6def0c593c96478bb52c959 to your computer and use it in GitHub Desktop.
Recorrido de arbol recursivo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
//recorre un arbol de forma recursiva hasta encontrar el nodo padre
var nodes = [
{
name: 'root1',
icon: 'fa fa-bath',
selected: true,
type: 'parent-tag'
},
{
name: 'root2',
icon: 'fa fa-bath',
selected: false,
type: 'sub-parent-tag',
children: [
{
name: 'child1',
id: 'child1ID',
icon: 'fa fa-bath',
selected: false,
type: 'tag',
},
{
name: 'child2',
id: 'child2ID',
icon: 'fa fa-bath',
selected: false,
type: 'sub-parent-tag',
children: [
{
name: 'grandchild1',
id: 'grandchild1_ID',
icon: 'fa fa-bath',
selected: false,
type: 'tag',
},
{
name: 'grandchild2',
id: 'grandchild2_ID',
icon: 'fa fa-bath',
selected: false,
type: 'tag',
}
]
}
]
}
];
function valueChange(){
var node = {
name: 'grandchild1',
id: 'grandchild1_ID',
icon: 'fa fa-bath',
selected: false,
type: 'tag',
};
console.log(node);
if (node.type === 'tag') {
let father = this.findFather(node, this.nodes);
console.log('pader',father);
}
}
function findFather(selectedNode, rootNode) {
if(rootNode.length > 0) {
const newRootNode = [];
console.log('rootNode' ,rootNode);
for (let i = 0; i < rootNode.length; i++) {
console.log('recorriendo RootNode' , rootNode[i]);
if (typeof rootNode[i].children !== 'undefined') {
for(let j = 0; j < rootNode[i].children.length; j++) {
console.log('recorriendo children' ,rootNode[i].children[j]);
if ( JSON.stringify(rootNode[i].children[j]) !== JSON.stringify(selectedNode) ) {
console.log('hijos' ,rootNode[i].children[j]);
newRootNode.push(rootNode[i].children[j]);
} else {
return rootNode[i];
}
}
} else if (rootNode[i].children === selectedNode) {
console.log('No tiene padres');
return rootNode[i];
}
}
this.findFather(selectedNode, newRootNode);
}
}
</script>
</head>
<body>
<button onclick="valueChange()">click</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment