递归地从嵌套数组中删除对象

Max*_*ich 2 javascript arrays recursion object

我有这样的数组。可以无限数量的嵌套

const myArray = [
  {
   id: 1, 
   children: [
              { 
                id: 3,
                children: []
              }
             ]
  },
  {
   id: 2, children: []
  }
]
Run Code Online (Sandbox Code Playgroud)

请帮助我通过 id 删除任何对象并返回没有它的新数组。

Ser*_* Tx 7

使用数组方法和递归函数:

function fn(arr, id) {
  return arr
    .filter((el) => el.id !== id)
    .map((el) => {
      if (!el.children || !Array.isArray(el.children)) return el;
      el.children = fn(el.children, id);
      return el;
    });
}

const myArray = [
  {
    id: 1,
    children: [
      {
        id: 3,
        children: [],
      },
    ],
  },
  {
    id: 2,
    children: [],
  },
];

console.log(fn(myArray,1))
console.log(fn(myArray,2))
console.log(fn(myArray,3))
Run Code Online (Sandbox Code Playgroud)


小智 7

recursiveRemove 函数将递归地从数组中删除元素并返回新列表。

map 函数创建数组中项目的副本,如果不需要保留原始数组的完整性,可以删除映射。

function recursiveRemove ( list, id ) {
    return list.map ( item => { return {...item} }).filter ( item => {
        if ( 'children' in item ) {
            item.children = recursiveRemove ( item.children, id );
        }
        return item.id !== id;
    });
}
const test1 = recursiveRemove ( myArray, 1);
const test2 = recursiveRemove ( myArray, 2);
const test3 = recursiveRemove ( myArray, 3);
Run Code Online (Sandbox Code Playgroud)