Как найти элемент в массиве объектов неизвестной вложенности?
подскажите пожалуйста как можно с помощью рекурсии вытащить объект с id:3 через findItem (в find для итерации приходит только (3)
const items = [
{
title: 'Production',
id: 1,
subTasks: [
{
title: 'Production 1',
id: 2,
subTasks: [{ title: 'Production 1 - 1', id: 3 }, { title: 'Production 1 - 2', id: 4 }],
},
],
},
{
title: 'Test',
id: 5,
subTasks: [],
},
]
Буду очень благодарен за помощь!
Я остановился на этом...
function findItem(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].id !== 4) {
pow(arr[i].subTasks);
}
else {
console.log(arr[i]);
return;
}
}
}
findItem(items)
Ответы (1 шт):
Автор решения: HaZcker
→ Ссылка
Попробуйте так:
const items = [
{
title: 'Production',
id: 1,
subTasks: [{
title: 'Production 1',
id: 2,
subTasks: [{
title: 'Production 1 - 1',
id: 3
},
{
title: 'Production 1 - 2',
id: 4
}
],
}, ],
},
{
title: 'Test',
id: 5,
subTasks: [],
},
]
function findTaskById(id, arr) {
let result = arr.find((obj) => obj.id === id)
if (!result) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === id) {
return arr[id]
} else if ('subTasks' in arr[i]) {
result = findTaskById(id, arr[i].subTasks)
if (result) {
return result
}
}
}
}
return result
}
console.log(findTaskById(1, items))
console.log(findTaskById(3, items))
UDP
Обновил с учётом комментария от Laukhin Andrey