首页 > 解决方案 > 尝试在树javascript中递归查找元素

问题描述

我试图弄清楚如何在 json 树中递归搜索元素。例如,我现在正在尝试达到“水果”,但不知道该怎么做。这是我的 json 对象

[
    {
        "_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, tree) {
    if(tree.children.name == name {
        return tree;
    }

    if(tree.child == 0) {
        return
    }

    return findName(name, tree);
};

标签: javascript

解决方案


const object = [
    {
        "_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 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))


推荐阅读