Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
How do I deep filter array and keep array tree structure

I need to remove items from nested arrays. I successfully have done this, however I need to keep the complete structure of the tree. The current code outputs the things object and has the element removed where name equals 'child thing 1', however my result misses a lot of other data from the original tree.

I am using lodash and deepdash as I will be working with objects with many children.

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 Respostas
Responde à pergunta

0

Its unclear from your question what you're expected result is, as pointed out by @grodzi in the comments. However, it seems like you're just looking for a way to quickly delete sub-structures in an object while maintaining its overall integrity. Lodash provides some nifty functions that simplifies tasks like these.

Two that would help with the task at hand are get and 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
));

I think something like this would get the job done. Make sure to check this yourself though, with tests preferably if this is at all likely to be deployed.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda