JSFiddle - React, Tailwind, and code Playground
CSS
body{
white-space: pre
}
JavaScript
let needle = 6,
items = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4, children: [{ id: 6 }, { id: 7, children: [{ id: 8 }, { id: 9 }] }] }, { id: 5 }];
function foo(acc, el){
if(el.id === needle) return el
if(el.children) {
let result = el.children.reduce(foo, acc)
if (result) el.open = true
return result
}
return acc
}
let result = items.reduce(foo, null)
document.body.textContent = JSON.stringify(result)
document.body.textContent += '\n_________\n' + JSON.stringify(items, null, 3)