简体   繁体   English

尝试使用 jQuery/JavaScript 构建递归函数

[英]Trying to build a recursion function using jQuery/JavaScript

I'm currently trying to build a function that traverse through a nested object looking for a value that matches.我目前正在尝试构建一个函数,该函数遍历嵌套对象以查找匹配的值。 I created this custom code that checks each levels of object.我创建了这个自定义代码来检查对象的每个级别。 The problem how can repeat the function multiple times until it fetches or match with the value I'm looking for traversing to multiple levels.问题如何多次重复该函数,直到它获取或匹配我正在寻找遍历多个级别的值。

 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();

Not sure what your key names might be so providing generic function using Object.values() - let me know if you only expect key names to be species - will simplify then不确定您的键名可能是什么,因此使用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);

Use JSON.stringify() and a regular expression to simplify things:使用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"));

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();

Try this one.试试这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM