2017-08-24 51 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