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

182
Views
¿Cómo filtro en profundidad la matriz y mantengo la estructura del árbol de la matriz?

Necesito eliminar elementos de matrices anidadas. He hecho esto con éxito, sin embargo, necesito mantener la estructura completa del árbol. El código actual genera el objeto de las things y elimina el elemento donde el name es igual a 'child thing 1' , sin embargo, mi resultado pierde muchos otros datos del árbol original.

Estoy usando lodash y deepdash ya que estaré trabajando con objetos con muchos niños.

 deepdash(_); let things = { type: 'app', info: [], things: [{ name: 'something', good: false, }, { name: 'another thing', good: true, children: [{ name: 'child thing 1', good: false, }, { name: 'child thing 2', good: true, }, { name: 'child thing 3', good: false, }], }, { name: 'something else', good: true, subItem: { name: 'sub-item', good: false, }, subItem2: { name: 'sub-item-2', good: true, }, }], }; let filtrate = _.filterDeep(things, (value, key, parent) => { if (key == 'name' && parent.name !== 'child thing 1') return true; }); console.log({ filtrate });
 .as-console-wrapper { min-height: 100%!important; top: 0; }
 <script src="https://cdn.jsdelivr.net/npm/lodash/lodash.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/deepdash/browser/deepdash.min.js"></script>

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

0

No está claro a partir de su pregunta cuál es el resultado esperado, como lo señaló @grodzi en los comentarios. Sin embargo, parece que solo está buscando una manera de eliminar rápidamente subestructuras en un objeto mientras mantiene su integridad general. Lodash proporciona algunas funciones ingeniosas que simplifican tareas como estas.

Dos que ayudarían con la tarea en cuestión son get y omit

 const pathsToRemove = ['things.1.children.0']; // use object dot notation (.) even for array elements const restructure = (object, pathsToRemove) => pathsToRemove.reduce((acc, path) => { const parentPath = path.split('.').slice(0,-1).join('.'); const [targetPath] = path.split('.').slice(-1); let parent = _.get(acc, parentPath); if (parent.constructor === Array) { // this block is to prevent empty array items parent.splice(+targetPath, 1); return acc; } return _.omit(acc, path); }, object); console.log(JSON.stringify( restructure(things, pathsToRemove), null, 4 ));

Creo que algo como esto haría el trabajo. Sin embargo, asegúrese de verificar esto usted mismo, preferiblemente con pruebas si es probable que se implemente.

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!