繁体   English   中英

递归函数以在javascript中搜索json对象

[英]recursive function to search in json object in javascript

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

像:查找橙色-> gotopage-> orange_store->查找-> 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) 

暂无
暂无

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

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