从深度未知的嵌套数组中删除项目

Mor*_*erg 5 javascript arrays recursion nested lodash

我正在尝试根据正确匹配的数组从嵌套数组中删除项目。

适用三个要求:

  1. 阵列的深度未知。项目可以有嵌套的子项目。
  2. 仅应移除没有儿童的物品
  3. 如果这些项目不在匹配的数组中,则应将其删除

我构建了一个函数来递归地到达最深层次并根据 $match 数组过滤项目。

这是我的代码到目前为止的样子:

import * as lodash from "https://cdn.skypack.dev/lodash@4.17.21";

let filterRecursively = (arr, match) => {
  // Recursively go to the deepest array we can find
  arr.forEach(el => {
      arr = el.children ? filterRecursively(el.children, match) : arr
  });

  // If we are at the deepest level we filter the items ...
  if (arr[0] && arr[0].children === undefined) {
    return _.filter(arr, (item) => {
        return match.includes(item.name)
    })
  } else { // ... if not we just return the array as-is
    return arr
  }
}

let arr = [
  {
    'name': 'John',
    'children': [
      {
        'name': 'John',
        'children': [
          { 'name': 'John' },
          { 'name': 'Jane' },
          { 'name': 'Joe' }
        ]
      }]
  }, {
    'name': 'Jeff',
    'children': [
      {
        'name': 'Joe',
        'children': [
          { 'name': 'Jill' },
          { 'name': 'Jeff' },
          { 'name': 'Joe' }
        ]
      }]
  }];

let match = ['John', 'Joe'];
let result = filterRecursively(arr, match);

console.log(result);

Run Code Online (Sandbox Code Playgroud)
// Expected result:
 [
   {
     'name': 'John',
     'children': [
       {
         'name': 'John',
         'children': [
           { 'name': 'John' },
           { 'name': 'Joe' }
         ]
       }]
   }, {
     'name': 'Jeff',
     'children': [
       {
         'name': 'Joe',
         'children': [
           { 'name': 'Joe' }
         ]
       }]
   }];
Run Code Online (Sandbox Code Playgroud)
// Current output
[
    {
        "name": "Joe"
    }
]
Run Code Online (Sandbox Code Playgroud)

请参阅代码笔

top*_*are 1

let filterRecursively = (arr, match) => {
  // Recursively go to the deepest array we can find
  return arr
    .map((el) =>
      el.children
        ? { ...el, children: filterRecursively(el.children, match) }
        : el
    )
    .filter((el) => el.children || match.includes(el.name));
};
Run Code Online (Sandbox Code Playgroud)

我已经递归地更新了过滤器。

let filterRecursively = (arr, match) => {
  // Recursively go to the deepest array we can find
  return arr
    .map((el) =>
      el.children
        ? { ...el, children: filterRecursively(el.children, match) }
        : el
    )
    .filter((el) => el.children || match.includes(el.name));
};
Run Code Online (Sandbox Code Playgroud)