使用JavaScript从对象中删除

Mic*_*ips 17 javascript object

我有一个如下所示的对象:

const arr = [
  {
    name: 'FolderA',
    child: [
      {
        name: 'FolderB',
        child: [
          {
            name: 'FolderC0',
            child: [],
          },
          {
            name: 'FolderC1',
            child: [],
          },
        ],
      },
    ],
  },
  {
    name: 'FolderM',
    child: [],
  },
];
Run Code Online (Sandbox Code Playgroud)

我有一个字符串的路径:

var path = "0-0-1".
Run Code Online (Sandbox Code Playgroud)

我必须删除该对象:

{
    name: 'FolderC1',
    child: [],
 },
Run Code Online (Sandbox Code Playgroud)

我可以这样做,

arr[0].child[0].splice(1, 1);
Run Code Online (Sandbox Code Playgroud)

但我想动态地做.由于路径字符串可以是任何东西,我想要上面的"." 要动态创建的运算符和拼接定义,以便在特定位置进行拼接.

Nin*_*olz 17

您可以通过保存最后一个索引并返回实际索引的子项来减少索引.后来与最后一个索引拼接.

function deepSplice(array, path) {
    var indices = path.split('-'),
        last = indices.pop();

    indices
        .reduce((a, i) => a[i].child, array)
        .splice(last, 1);
}

const array = [{ name: 'FolderA', child: [{ name: 'FolderB', child: [{ name: 'FolderC0', child: [] }, { name: 'FolderC1', child: [] }] }] }, { name: 'FolderM', child: [] }];

deepSplice(array, "0-0-1");
console.log(array);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)