Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
Javascript: objeto de filtro que contiene matrices con valor de otra matriz

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 !

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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; }

about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!