Tengo un problema al implementar el filtrado de datos anidados. Tengo este tipo de datos de la API:
const animals = { bugs: ['ant', 'cricket'], fish: ['shark', 'whale', 'tuna'], mammals: ['cow', 'horse', 'sheep'], birds: ['eagle', 'crow', 'parrot'], predators: ['tiger', 'lion'] } Tengo que filtrarlos con esta matriz: const data = ['shark', 'horse', 'cow', 'parrot']
El resultado que quiero lograr:
const filtered = { fish: ['shark'], mammals: ['cow', 'horse'], birds: ['parrot'], }Yo he tratado :
filter.forEach((item) => { for (let key in animals) { let species = [] if (animals[key].includes(item)) { filtered[key] = [...species, species] } } })y el resultado:
const filtered = { fish: ['whale'], mammals: ['cow',], birds: ['parrot'], }Todavía no puedo lograr el resultado deseado, porque los elementos dentro de la matriz no se agregarán sino que se reemplazarán. Estoy atorado aqui. Cualquier ayuda será muy apreciada. Gracias !
Primero debe hacer un bucle en su objeto y luego filtrar matrices de animales según los datos.
const animals = { fish: ['shark', 'whale', 'tuna'], mammals: ['cow', 'horse', 'sheep'], birds: ['eagle', 'crow', 'parrot'],}; const data = ['shark', 'horse', 'cow', 'parrot']; let filtered = {}; for (var a of Object.keys(animals)) { filtered[a] = animals[a].filter(value => data.includes(value)); } console.log(filtered);Podría reconstruir las entradas del objeto.
const animals = { bugs: ['ant', 'cricket'], fish: ['shark', 'whale', 'tuna'], mammals: ['cow', 'horse', 'sheep'], birds: ['eagle', 'crow', 'parrot'], predators: ['tiger', 'lion'] }, data = ['shark', 'horse', 'cow', 'parrot'], result = Object.fromEntries(Object .entries(animals) .flatMap(([k, a]) => { a = a.filter(v => data.includes(v)); return a.length ? [[k, a]] : [] }) ); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }Puedes usar el método de filter :
const fish = animals.fish.filter((animal) => animal === 'shark'); const mammals = animals.mammals.filter((animal) => animal === 'cow' || animal === 'horse'); const birds = animals.birds.filter((animal) => animal === 'parrot'); const filtered = { fish, // equals to fish: fish mammals, // equals to mammals: mammals birds, // equals to birds: birds };Tenga en cuenta que esto es solo un ejemplo. Puede poner sus propios controles en las funciones de devolución de llamada, pero debería devolver un valor booleano.