I was just practicing some native Javascript and came across this problem. I’m building a comments widget and trying to implement a ‘reply’ button. For this I have to iterate through some n number of nested comments to find the correct one and push the reply to it’s ‘responses’ attribute. This is my code so far:
const recursiveSearch = (object, target) => {
if(object.id === target) return object;
let result;
if(object.responses.length > 0) {
object.responses.forEach(response => {
if(response.id === target) {
result = response;
console.log('match found')
console.log(response)
return response
}
else if(response.responses.length > 0) recursiveSearch(response, target)
})
};
console.log('result Is')
console.log(result)
return result
}
The logs show the expected behavior just fine but when looking at the end return statement is undefined. Any way to get around this?