JavaScript: Find all parents for element in tree recursive
You could use a recursive approach by checking the name and return a new data structure with only the nodes to the wanted object.
function find({ tree = [], ...object }, name) {
var result;
if (object.name === name) return object;
return tree.some(o => result = find(o, name)) && Object.assign({}, object, { tree: [result] });
}
var datas = { tree: [{ name: 'name1', tree: [{ name: 'name2' }, { name: 'name3' }, { name: 'name4', tree: [{ name: 'name5' }, { name: 'name6' }] }, { name: 'name7' }] }, { name: 'name8', tree: [{ name: 'name9' }] }] };
console.log(find(datas, 'name5'));
.as-console-wrapper { max-height: 100% !important; top: 0; }