gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:46:09 25 4
gpt4 key购买 nike

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

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

最佳答案

不确定您的键名可能是什么,因此使用 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);

关于javascript - 尝试使用 jQuery/JavaScript 构建递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59296848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com