¿Es posible usar el método find() dentro de una matriz de profundidad x?
Por ejemplo, supongamos que tengo la siguiente matriz de objetos, llámela test :
[ { "id": "1", "title": "First", }, { "id": "2", "title": "Second", "movies": [ { "id": "3", "title": "Happy Gilmore", "Actors": [ { "id": "4", "title": "John Doe", }, { "id": "5", "title": "Jane Doe", }, ], "Producers": [ { "id": "6", "title": "Max Smith", }, { "id": "7", "title": "Richard Rocky", }, ], }, { "id": "10", "title": "Billy Madison", "Actors": [ { "id": "40", "title": "John Smith", }, { "id": "50", "title": "Alex Doe", }, ], "Producers": [ { "id": "60", "title": "Bob Smith", }, { "id": "70", "title": "Polly Rocky", }, ], } ] } ] Supongamos que estoy buscando la identificación "2". Puedo usar el método find() para buscar el primer nivel de la matriz y devolver el objeto deseado haciendo test.find(element => element.id === "2") .
Sin embargo, supongamos que ahora estoy buscando la ocurrencia donde la identificación es 4. Como puede ver en el JSON anterior, ese elemento está dentro de una submatriz dentro de test . ¿Hay alguna manera, por lo tanto, en la que aún pueda buscar a través de la test para encontrar el elemento donde id = 4?
find no puede hacer esto, pero puede usarlo en un enfoque recursivo:
function findDeep(arr, predicate) { let res = arr.find(predicate); if (res !== undefined) return res; for (let obj of arr) { for (let value of Object.values(Object(obj)).filter(Array.isArray)) { res = findDeep(value, predicate); if (res !== undefined) return res; } } } let test = [{"id": "1","title": "First",},{"id": "2","title": "Second","movies": [{"id": "3","title": "Happy Gilmore","Actors": [{"id": "4","title": "John Doe",},{"id": "5","title": "Jane Doe",},],"Producers": [{"id": "6","title": "Max Smith",},{"id": "7","title": "Richard Rocky",},],},{"id": "10","title": "Billy Madison","Actors": [{"id": "40","title": "John Smith",},{"id": "50","title": "Alex Doe",},],"Producers": [{"id": "60","title": "Bob Smith",},{"id": "70","title": "Polly Rocky",},],}]}]; let res = findDeep(test, obj => obj.id == "4"); console.log(res);