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.
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)