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

179
Visualizações
Filter array of infinitely nested objects

Let's say I have an array of nested objects such as:

const data = [
    {
        id: 1,
        children:[
            {
                id: 2,
                children:[
                    {
                        id: 3,
                        children:[
                            {
                                id: 4,
                                children: [],
                            },
                            {
                                id: 5,
                                children: [],
                            }
                        ],
                    },
                ],
            },
        ],
    },
    {
        id: 8,
        children:[
            {
                id: 9,
                children:[
                    {
                        id: 10,
                        children:[],
                    },
                ],
            },
        ],
    },
];

And I would like to return a new array with id: 3 excluded for example. So it would become:

const data = [
    {
        id: 1,
        children:[
            {
                id: 2,
                children:[],
            },
        ],
    },
    {
        id: 8,
        children:[
            {
                id: 9,
                children:[
                    {
                        id: 10,
                        children:[],
                    },
                ],
            },
        ],
    },
];

The excluded id can be from any level, and it and its children should be removed. What's the best approach to do this? I've tried several other solutions with no luck so far.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use recursion and Array.reduce,..

eg.

const data=[{id:1,children:[{id:2,children:[{id:3,children:[{id:4,children:[]},{id:5,children:[]}]},]},]},{id:8,children:[{id:9,children:[{id:10,children:[]},]},]},]


function removeId(data, id) {
  return data.reduce((a,v) => {
    if (v.id !== id) 
       a.push({...v, children: removeId(v.children, id)});
    return a;
  }, []);
}

const r = removeId(data, 3);

console.log(r);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use a combination of JSON.parse and JSON.stringify to reach each node of the object:

JSON.parse(JSON.stringify(data, (key, value) => {
   // If children is an array and it contains an id equal to 3, we filter out that child
   if (key === 'children' && value instanceof Array) return value.filter(x=>x.id!==3);
   // Otherwise we don't intervene
   return value;
}));

Example:

const data = [
    {
        id: 1,
        children:[
            {
                id: 2,
                children:[
                    {
                        id: 3,
                        children:[
                            {
                                id: 4,
                                children: [],
                            },
                            {
                                id: 5,
                                children: [],
                            }
                        ],
                    },
                ],
            },
        ],
    },
    {
        id: 8,
        children:[
            {
                id: 9,
                children:[
                    {
                        id: 10,
                        children:[],
                    },
                ],
            },
        ],
    },
];

console.log(JSON.parse(JSON.stringify(data, (key, value) => {
   if (key === 'children' && value instanceof Array) return value.filter(x=>x.id!==3);
   return value;
})));

Since the two JSON methods are natively implemented by browsers, this solution is usually faster

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