Cette fonction est universelle et effectue une recherche récursive. Peu importe si l'arbre d'entrée est un objet (racine unique) ou un tableau d'objets (plusieurs objets racine). Vous pouvez configurer le nom du prop qui contient le tableau des enfants dans les objets de l'arbre.
// 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
}
}
Je l'ai testé en local et il fonctionne bien, mais il ne fonctionne pas sur jsfiddle ou jsbin... (problèmes de récurrence sur ces sites ? ?).
code d'exécution :
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);
Il fonctionne en http://www.pythontutor.com/live.html#mode=edit (coller le code)
2 votes
Avez-vous essayé la récursion ?
59 votes
@ShoaibShaikh : Pour comprendre la récursion, il faut d'abord comprendre la récursion.
1 votes
Votre structure de données ressemble-t-elle vraiment à ça ? Vous stockez vos nœuds enfants dans un tableau, mais ils sont enveloppés dans un seul objet.
{}
. Vous avez spécifié deuxtitle
et deux attributschildren
par exemple, comme enfants de "topNode".0 votes
Lol, c'est une bonne blague @Rocket Hazmat ( stackoverflow.com/users/206403/rocket-hazmat ), vient de poster un graphique ( pbs.twimg.com/media/DhnUDIRWsAoYBXo.jpg ) de celui-ci ici sur Twitter.