Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda