clestcruz
clestcruz

Reputation: 1111

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

Upvotes: 1

Views: 78

Answers (3)

symlink
symlink

Reputation: 12209

Use JSON.stringify() and a regular expression to simplify things:

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

Upvotes: 1

Amit Sinha
Amit Sinha

Reputation: 108

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.

Upvotes: 0

mickl
mickl

Reputation: 49945

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

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

Upvotes: 1

Related Questions