Este la función es universal y busca de forma recursiva. No importa, si el árbol de entrada es un objeto (raíz única) o una matriz de objetos (muchos objetos raíz). Puede configurar el nombre de utilería que contiene la matriz de elementos secundarios en objetos de árbol.
// Searches items tree for object with specified prop with value
//
// @param {object} tree nodes tree with children items in nodesProp[] table, with one (object) or many (array of objects) roots
// @param {string} propNodes name of prop that holds child nodes array
// @param {string} prop name of searched node's prop
// @param {mixed} value value of searched node's prop
// @returns {object/null} returns first object that match supplied arguments (prop: value) or null if no matching object was found
function searchTree(tree, nodesProp, prop, value) {
var i, f = null; // iterator, found node
if (Array.isArray(tree)) { // if entry object is array objects, check each object
for (i = 0; i < tree.length; i++) {
f = searchTree(tree[i], nodesProp, prop, value);
if (f) { // if found matching object, return it.
return f;
}
}
} else if (typeof tree === 'object') { // standard tree node (one root)
if (tree[prop] !== undefined && tree[prop] === value) {
return tree; // found matching node
}
}
if (tree[nodesProp] !== undefined && tree[nodesProp].length > 0) { // if this is not maching node, search nodes, children (if prop exist and it is not empty)
return searchTree(tree[nodesProp], nodesProp, prop, value);
} else {
return null; // node does not match and it neither have children
}
}
he comprobado necesitas cigarros y funciona bien, pero de alguna manera no se ejecutará en jsFiddle o jsbin ... (temas recurency en esos sitios ??)
código
de ejecución:
var data = [{
title: 'topNode',
children: [{
title: 'node1',
children: [{
title: 'randomNode_1'
}, {
title: 'node2',
children: [{
title: 'randomNode_2',
children: [{
title: 'node2',
children: [{
title: 'randomNode_3',
}]
}]
}]
}]
}]
}];
var r = searchTree(data, 'children', 'title', 'randomNode_1');
//var r = searchTree(data, 'children', 'title', 'node2'); // check it too
console.log(r);
funciona en http://www.pythontutor.com/live.html#mode=edit (pegar el código)
¿Has probado la recursión? –
@ShoaibShaikh: Para comprender la recursión, primero se debe entender la recursión. –
¿Su estructura de datos realmente se ve así?Está almacenando sus nodos secundarios en una matriz, pero están envueltos en un solo objeto '{}'. Ha especificado dos atributos 'title' y dos' children', por ejemplo, como secundarios de "topNode". – voithos