這函數是通用的,並且遞歸地進行搜索。 如果輸入樹是對象(單根)或對象數組(很多根對象),則無關緊要。您可以配置在樹對象中保存children數組的prop名稱。
// 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
}
}
我localy測試,它工作正常,但它在某種程度上不會(在這些網站?recurency問題)
運行代碼上的jsfiddle或jsbin運行...:
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);
它工作在http://www.pythontutor.com/live.html#mode=edit(粘貼代碼)
來源
2017-10-24 16:05:27
Tom
你試過遞歸嗎? – 2012-02-03 18:25:42
@ShoaibShaikh:爲了理解遞歸,首先必須理解遞歸。 – 2012-02-03 18:30:35
你的數據結構真的看起來像那樣嗎?您將您的子節點存儲在一個數組中,但它們被封裝在一個對象'{}'中。例如,您已經指定了兩個'title'屬性和兩個'children',作爲「topNode」的子節點。 – voithos 2012-02-03 18:33:37