How to break and return from recursive functions?

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 this?

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); 
+6
source share
1 answer

If a match is found, you need to return the value. And in the parent call, if the recursive call returns a value, it should also return that value. You can change your code as follows

 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' } 
+8
source

Source: https://habr.com/ru/post/979627/


All Articles