I am trying to write a recursive function in javascript but not work properly. i have a json array of objects data where i want to find something based on key then find again based on gotopage key in search object.
like : find orange -> gotopage -> orange_store ->find -> orange_store -> gotopage -> yellow_store -> find so the same process goes in recursively.can you please help where i'm going wrong in my approach.
[
{
"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));
output for first iteration but not work for every iteration:
Object {id: 1, find: "orange", gotopage: "orange_store"}
Object {id: 2, find: "orange_store", gotopage: "yellow_store"}
searchRecbut never returning null. In javascript, indexing a missing element in an array will yieldundefinednotnull.