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

时间:2017-08-24 15:23:52

标签: javascript arrays json loops recursion

我正在尝试在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"}

1 个答案:

答案 0 :(得分:2)

使用递归的另一个例子。我做一个简单的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)