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

153
Visualizações
Iterate through a specific nested object key

There is an object like:

props = {
  any: 'thing',
  intro: { content: 'foo' }
}

Now I want to loop through a given string representing a specific path (props.intro.content) in a way to set the deepest value to undefined:

props.intro.content = undefined
props.intro = undefined
props = undefined

So the results by iterating the path given above should output these three objects:

{
  any: 'thing',
  intro: { content: undefined }
},
{
  any: 'thing',
  intro: undefined
},
undefined

I tried to use split and for loop

const array = 'props.intro.content'.split('.')

for (let index = array.length - 1; index > -1; index--) {
  console.log([array.join('.')]) // this returns the flatten path
  array.pop()
}

but this doesn't handle the object itself, so I do not get the correct object as output.

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

0

Here's a recursive function that does that. I made the example extra deep to show that it's robust to deep nesting.

The one tricky part is the last one you should get just undefined if the path starts with the variables name. You can't get the name of the variable referencing the object you pass into the function, so maybe you can add a boolean parameter that pushes undefined to the end of the array, and have the string input start at the first key layer.

const object = {
  any: 'thing',
  intro: { 
    content: {
      lets: {
        go: {
          deeper: 20
        }
      }
    } 
  }
}

function deepDelete (mainObj, locations) {
  const props = locations.split('.')
  const outputs = [];
  
  function recurseDelete(obj, props, mainObj) {
    if (props.length === 0) return
 
    recurseDelete(obj[props[0]], props.slice(1), mainObj)
    obj[props[0]] = undefined
    outputs.push(structuredClone(mainObj))
  }
  recurseDelete(mainObj, props, mainObj);
  return outputs
}

const locations = 'intro.content.lets.go.deeper';
const outputArray = deepDelete(object, locations)
console.log(outputArray)

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