递归函数,用于在 JavaScript 中的 JSON 对象中搜索



我正在尝试用javascript编写一个递归函数,但无法正常工作。 我有一个 JSON 对象数据数组,我想根据键查找某些内容,然后根据搜索对象中的 GotoPage 键再次查找。

比如:找到橙色 -> gotopage -> orange_store ->find -> orange_store -> gotopage -> yellow_store -> 查找,以便相同的过程递归进入。您能否帮助我在方法中出错的地方。

[
{
"id": 1,
"find": "orange",
"gotopage": "orange_store"
},
{
"id": 2,
"find": "orange_store",
"gotopage": "yellow_store"
},
{
"id": 3,
"find": "black_store",
"gotopage": "black_store"
},
{
"id": 4,
"find": "yellow_store",
"gotopage": "white_store"
},
{
"id": 5,
"find": "black_store",
"gotopage": "red_store"
}
]

function searchRec(search, myArray) {
for (var i = 0; i < myArray.length; i++) {
var res = [];
if (myArray[i].find == search) {
if (myArray[i] !== null) {
console.log(myArray[i]);
res = searchRec(myArray[i].gotopage, myArray);
if (res !== null) {
return res;
}
return myArray[i];
}
}
}
}
function findNode(arr) {
for (i = 0; i < arr.length; i++) {
searchRec(arr[i].find, arr);
break;
}
}
console.log(findNode(json));

第一次迭代的输出,但不适用于每次迭代:

Object {id: 1, find: "orange", gotopage: "orange_store"}
Object {id: 2, find: "orange_store", gotopage: "yellow_store"}

另一个使用递归的例子。我做了一个简单的forEach()来找到你要找的东西,并将其存储在变量中,记录它,然后用我们新创建的值重新调用函数。如果找不到任何内容,则返回 null 并结束。

const data = [
{
"id": 1,
"find": "orange",
"gotopage": "orange_store"
},
{
"id": 2,
"find": "orange_store",
"gotopage": "yellow_store"
},
{
"id": 3,
"find": "black_store",
"gotopage": "black_store"
},
{
"id": 4,
"find": "yellow_store",
"gotopage": "white_store"
},
{
"id": 5,
"find": "black_store",
"gotopage": "red_store"
}
];
function recursiveStore(search, myArray) {
let obj = {}
let newSearch;
data.forEach(store => {
if (search === store.find) {
obj = store
newSearch = store.gotopage 
} 
})
if (Object.keys(obj).length === 0) {
return null
}
console.log(obj)
recursiveStore(newSearch, myArray)
}
recursiveStore("orange", data)

最新更新