function findName(name,children) {
if (Array.isArray(children)) {
// Yes,check them
for (const childNode of children) {
if (childNode.name === name) {
// Found it
return childNode;
}
// Look in this node's children
const found = findName(name,childNode.children);
if (found) {
// Found in this node's children
return found;
}
}
}
}
现场示例:
const tree = [
{
"_id": "604cab0acbdb8c1060698419","name": "Grocery","children": [
{
"children": [
{
"name": "Fruits","price": "200"
}
],"_id": "604cad9b4ae51310c6f313f6","name": "Potatoes","price": "200"
},{
"children": [],"_id": "604cae721257d510e679a467","name": "Vegetables"
}
],"date": "2021-03-13T12:07:38.186Z","__v": 0
} ];
function findName(name,childNode.children);
if (found) {
// Found in this node's children
return found;
}
}
}
}
console.log(findName("Fruits",tree));
,
const object = [
{
"_id": "604cab0acbdb8c1060698419","children": [
{
"children": [
{
"name": "Fruits","price": "200"
}
],"price": "200"
},{
"children": [],"name": "Vegetables"
}
],"__v": 0
} ]
function find(name,tree) {
// tree is undefined,return `undefined` (base case)
if (!tree) return
if (Array.isArray(tree)) {
// tree is an array
// so iterate over every object in the array
for (let i = 0; i < tree.length; i++) {
const obj = tree[i]
const result = find(name,obj)
// `find` returned non-undefined value
// means match is found,return it
if (result) return result
// no match found in `obj` so continue
}
} else if (tree.name === name) {
// `tree` is a key-value object
// and has matching `name`
return tree
}
// if no tree matching `name` found on the current `tree`
// try finding on its `children`
return find(name,tree.children)
}
console.log(find("Fruits",object))