Using the following code, the function returns several times. I need to break the recursion and return the result only once.
Any idea how to fix it?
http://jsfiddle.net/xhe6h8f0/
var data = {
item: [{
itemNested: [{
itemNested2: [{
id: "2"
}]
}]
}]
};
function findById (obj, id) {
var result;
for (var p in obj) {
if (obj.id) {
if(obj.id == id) {
result = obj;
break; // PROBLEM HERE dos not break
}
} else {
if (typeof obj[p] === 'object') {
findById(obj[p], id);
}
}
}
console.log(result);
return result;
}
var result = findById(data, "2");
alert(result);
One way to break out of a recursive function in Python is to throw an exception and catch that at the top level. Some people will say that this is not the right way to think about recursion, but it gets the job done.
You can make use of the class. Initialize a variable self. flag=False in the init method, when you find the solution change self. flag = True and return None when self.
Use a return; statement where the code needs to stop and go back to its predecessor (which will in turn also call the return; , and so on...)
If the match is found, then you need to return the value. And in the parent call, if the recursive call returns a value, then it also has to return that value. You can modify your code like this
function findById(obj, id) {
var result;
for (var p in obj) {
/*
if `id` is not in `obj`, then `obj.id` will evaluate to
be `undefined`, which will not be equal to the `id`.
*/
if (obj.id === id) {
return obj;
} else {
if (typeof obj[p] === 'object') {
result = findById(obj[p], id);
if (result) {
return result;
}
}
}
}
return result;
}
Now,
var result = findById(data, "2");
console.log(result);
will print
{ id: '2' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With