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

151
Views
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 answers
Answer question

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 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!