遍历特定嵌套对象键。

3
有一个像这样的对象:
props = {
  any: 'thing',
  intro: { content: 'foo' }
}

现在我希望能够循环遍历给定的字符串,该字符串代表了一个特定路径(props.intro.content),以便将最深处的值设置为undefined:
props.intro.content = undefined
props.intro = undefined
props = undefined

通过迭代上述路径得到的结果应输出以下三个对象:

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

我尝试使用分割和循环

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()
}

但是这种方法并没有处理对象本身,因此输出的结果不正确。


你不能从对象本身访问指向该对象的变量。 - Barmar
1
你正在寻找mpath - bogdanoff
还有path-value - vitaly-t
1个回答

1
这是一个递归函数,用于实现这个功能。我将示例设置得很深,以展示它对深度嵌套的鲁棒性。
唯一棘手的部分是最后一个,如果路径以变量名称开头,则应该只返回undefined。您无法获取传递到函数中的对象引用的变量名称,因此可以添加一个布尔参数,将undefined推送到数组末尾,并使字符串输入从第一个键层开始。

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)


谢谢。我在使用Node 16时遇到了“ReferenceError: structuredClone未定义”的问题。 - user3142695
嗯,那么不要使用structuredClone(mainObj),尝试使用JSON.parse(JSON.stringify(mainObj)) - Brother58697
你不能只使用扩展运算符吗:outputs.push({...mainObj}) - user3142695
只有一级深度的内容会进行深拷贝,更深层次的内容则进行浅拷贝。这也是我将示例设置得更加深入的原因。我最初使用了Object.assign(),它也只能进行浅拷贝,当你深入到更深层次时就无法正常工作了。 - Brother58697

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接