const data = [
{
"id": "1",
"sub": [
{
"id": "2",
"sub": [
{
"id": "3",
"sub": null
},
{
"id": "4",
"sub": [
{
"id": "6",
"sub": null
}
]
},
{
"id": "5",
"sub": null
}
]
}
]
},
{
"id": "7",
"sub": [
{
"id": "8",
"sub": [
{
"id": "9",
"sub": [
{
id: "15",
sub: null
}
]
}
]
}
]
},
{
"id": "10",
"sub": null
}
];
function findPath(data, id) {
const result = [];
function find(data, id) {
const index = data.findIndex(item => item.id === id);
if (index >= 0) {
result.push(id);
return result;
}
for (let i = 0; i < data.length; i++) {
if (data[i].sub) {
result.push(data[i].id);
find(data[i].sub, id);
if (result.includes(id)) {
return;
}
result.pop();
}
}
}
find(data, id);
return result;
}
console.log(findPath(data, "2"));
console