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 (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' }
source share