2017-08-24 32 views
1

我想在javascript中编写递归函数,但无法正常工作。我有一个json数组对象数据,我想根据键找到某些东西,然后再根据搜索对象中的gotopage键找到它。在javascript中搜索json对象的递归函数

like:find orange - > 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"} 
+0

为什么第三对象找不到:yellow_store? –

+0

您正在检查从'searchRec'返回的null,但永远不会返回null。在JavaScript中,索引数组中的缺失元素将产生'undefined'而不是'null'。 – ivo

回答

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)

+0

感谢@christopher寻求最佳解决方案。我想返回obj而不是console.log? – truesource

+0

哪个对象?他们全部? –

+0

是我想要返回的所有结果。 – truesource