小编jsN*_*00b的帖子

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

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

适用三个要求:

  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 …
Run Code Online (Sandbox Code Playgroud)

javascript arrays recursion nested lodash

5
推荐指数
1
解决办法
816
查看次数

标签 统计

arrays ×1

javascript ×1

lodash ×1

nested ×1

recursion ×1