【问题标题】:Trying to build a recursion function using jQuery/JavaScript尝试使用 jQuery/JavaScript 构建递归函数
【发布时间】:2020-04-05 09:18:53
【问题描述】:

我目前正在尝试构建一个遍历嵌套对象以查找匹配值的函数。我创建了这个自定义代码来检查每个级别的对象。问题是如何多次重复该函数,直到它获取或匹配我正在寻找遍历多个级别的值。

let animalTree = {
    "animals":[
      {
        "species":"Vertebrates", 
        "types": [
            {
                "category": "Fish",
            },
            {
                "category": "Amphibians",
            },
            {
                "category": "Reptiles",
            },
            {
                "category": "Birds",
            },
            {
                "category": "Mammals",
            }
        ]
      }, 
      {
        "species":"Invertebrates", 
      },
      {
        "species":"Annelids", 
      },
      {
        "species":"Molluscs", 
      },
      {
        "species":"Nematodes", 
      },
      {
        "species":"Arthropods", 
      },
    ],
}





let scanTree = () => {

    let matchValue = "Vertebrates";

    for (let i = 0; i < animalTree.length; i++){

        if (animalTree[i].species == matchValue){
            console.log('Found')
        }
    }
}

let jParse = JSON.stringify(animalTree);

scanTree();

【问题讨论】:

  • 你的匹配值是否可以是categoryspecie 为什么要递归运行你的函数?
  • 子元素必须有相同的键名
  • 如果您的 JSON 中有第二项,那会是什么样子?你是说可能还有另一个animals 对象吗?您的问题有点令人困惑-您不需要为此编写自己的函数..
  • @mickl 是的,匹配值可以是物种或类别
  • 这个问题没有 JSON。 JSON 是一种文本格式。你所拥有的是一个对象。不需要任何(额外的)特殊行话。

标签: javascript jquery recursion


【解决方案1】:

不确定您的键名可能是什么,因此使用 Object.values() 提供通用功能 - 如果您只希望键名是物种,请告诉我 - 然后会简化

let animalTree = {
    "animals":[
      {
        "species":"Vertebrates", 
        "types": [
            {
                "category": "Fish",
            },
            {
                "category": "Amphibians",
            },
            {
                "category": "Reptiles",
            },
            {
                "category": "Birds",
            },
            {
                "category": "Mammals",
            }
        ]
      }, 
      {
        "species":"Invertebrates", 
      },
      {
        "species":"Annelids", 
      },
      {
        "species":"Molluscs", 
      },
      {
        "species":"Nematodes", 
      },
      {
        "species":"Arthropods", 
      },
    ],
}

let matchValue = "Birds";

let scan = (array) => {
  for(let item of array) {      
      for(let value of Object.values(item)){
          if(typeof value === "string" && value === matchValue) {
              return item;
          } else if (Array.isArray(value)) {
             return scan(value);
          }
      }
  }
}


let result = scan(animalTree.animals);
console.log(result);

【讨论】:

    【解决方案2】:

    使用JSON.stringify() 和正则表达式来简化事情:

    const scanTree = (str) => { 
       const arr = JSON.stringify(animalTree).match(/"\w+":\s?"\w+"/g);
       const res = arr.filter((el) => el.indexOf(str) > -1);
       return res.map(val => JSON.parse("{" + val + "}"));
    }
    

    const animalTree = {
        "animals":[
          {
            "species":"Vertebrates", 
            "types": [
                {
                    "category": "Fish",
                },
                {
                    "category": "Amphibians",
                },
                {
                    "category": "Reptiles",
                },
                {
                    "category": "Birds",
                },
                {
                    "category": "Mammals",
                }
            ]
          }, 
          {
            "species":"Invertebrates", 
          },
          {
            "species":"Annelids", 
          },
          {
            "species":"Molluscs", 
          },
          {
            "species":"Nematodes", 
          },
          {
            "species":"Arthropods", 
          },
        ],
    };
    
    const scanTree = (str) => { 
       const arr = JSON.stringify(animalTree).match(/"\w+":\s?"\w+"/g);
       const res = arr.filter((el) => el.indexOf(str) > -1);
       return res.map(val => JSON.parse("{" + val + "}"));
    }
    
    console.log(scanTree("Birds"));

    【讨论】:

      【解决方案3】:
      let animalTree = {
              "animals":[
                {
                  "species":"Vertebrates", 
                  "types": [
                      {
                          "category": "Fish",
                      },
                      {
                          "category": "Amphibians",
                      },
                      {
                          "category": "Reptiles",
                      },
                      {
                          "category": "Birds",
                      },
                      {
                          "category": "Mammals",
                      }
                  ]
                }, 
                {
                  "species":"Invertebrates", 
                },
                {
                  "species":"Annelids", 
                },
                {
                  "species":"Molluscs", 
                },
                {
                  "species":"Nematodes", 
                },
                {
                  "species":"Arthropods", 
                },
              ],
          }
      
          let scanTree = () => {
              var flag = 0;
              let matchValue = "Vertebrates";
              for(let i = 0 ; i < animalTree.animals.length ; i++ ){
                  if(animalTree.animals[i].species == matchValue){
                      flag = 1;
                      console.log("found");
                      break;
                  }
                  else{
                      flag = 0;
                  }
              }
              if(!flag){
                  console.log("not found")
              }
          }
      
          //let jParse = JSON.stringify(animalTree);
      
          scanTree();
      

      试试这个。

      【讨论】:

        猜你喜欢
        • 2020-02-27
        • 2021-04-17
        • 2013-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-12
        • 2020-01-19
        • 2019-04-14
        相关资源
        最近更新 更多