有一个类似以下对象的对象:

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

现在,我想遍历表示specific路径(props.intro.content)的给定字符串,将最深的值设置为undefined:

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

因此,通过迭代上面给出的路径得到的结果应该输出以下三个对象:

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

我try 使用Split和For循环

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

但这并不处理对象本身,所以我没有得到正确的对象作为输出.

推荐答案

下面是一个执行此操作的递归函数.我把这个例子做得特别深,以表明它对深度嵌套是健壮的.

最后一个棘手的部分是,如果路径以变量名称开头,则应该只得到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)

Javascript相关问答推荐

提交表格后保留Web表格中的收件箱值?

react/redux中的formData在expressjs中返回未定义的req.params.id

Exceljs:我们在file.xlsx(...)&#中发现了一个问题'"" 39人;

Next.js(react)使用moment或不使用日期和时间格式

引用在HTMLAttributes<;HTMLDivElement>;中不可用

为什么我的导航条打开状态没有在窗口addeventlistener(Reaction Js)中更新?

无法使用单击按钮时的useState将数据从一个页面传递到另一个页面

将内容大小设置为剩余可用空间,但如果需要,可在div上显示滚动条

为什么我的getAsFile()方法返回空?

以Angular 实现ng-Circle-Progress时出错:模块没有导出的成员

用于在路径之间移动图像的查询

回溯替代方式

当我点击一个按钮后按回车键时,如何阻止它再次被点击

我怎样才能得到一个数组的名字在另一个数组?

ReferenceError:无法在初始化之前访问setData

使用createBrowserRoutVS BrowserRouter的Reaction路由

TypeORM QueryBuilder限制联接到一条记录

为什么我的SoupRequest";被重置为初始值,以及如何修复它?

检测带有委托的元素内部的点击,以及元素何时按其类名被选中

如何动态呈现适合未知屏幕大小的最大数量的表行?苗条的