【问题标题】:How to filter a tree structure while keeping the decendants of the parents that are filtered out?如何过滤树结构,同时保留被过滤掉的父母的后代?
【发布时间】:2021-12-29 09:37:04
【问题描述】:

所以我有以下树结构:

const tree = {
  id: "1",
  tag: "pending",
  subtasks: [
    { id: "2", tag: "pending", subtasks: [] },
    {
      id: "3",
      tag: "in progress",
      subtasks: [
        {
          id: "4",
          tag: "pending",
          subtasks: [
            {
              id: "6",
              tag: "in progress",
              subtasks: [
                {
                  id: "10",
                  tag: "pending",
                  subtasks: [{ id: "11", tag: "complete", subtasks: [] }]
                }
              ]
            },
            { id: "7", tag: "complete", subtasks: [] }
          ]
        },
        { id: "5", tag: "pending", subtasks: [] }
      ]
    },
    { id: "4", tag: "complete", subtasks: [] }
  ]
};

我想删除任何具有“进行中”tag 的节点。但是,如果他们的tags 没有“进行中”,我也想保留已删除节点的子节点。将通过将它们移动到与其父级相同的深度和索引级别来保留它们。

所以,结果将如下所示:

const filteredTree = {
  id: "1",
  tag: "pending",
  subtasks: [
    { id: "2", tag: "pending", subtasks: [] },
    {
      id: "4",
      tag: "pending",
      subtasks: [
        {
          id: "10",
          tag: "pending",
          subtasks: [{ id: "11", tag: "complete", subtasks: [] }]
        },
        { id: "7", tag: "complete", subtasks: [] }
      ]
    },
    { id: "5", tag: "pending", subtasks: [] },
    { id: "4", tag: "complete", subtasks: [] }
  ]
};

我怎样才能做到这一点?

【问题讨论】:

  • 你尝试了什么?

标签: javascript typescript filter tree


【解决方案1】:

您可以通过检查tag 来删除,并获取过滤后的subtasks 或过滤后的subtasks 的新对象。

const
    remove = tag => ({ subtasks, ...node }) => {
        subtasks = subtasks.flatMap(remove(tag));
        return node.tag === tag
            ? subtasks
            : [{ ...node, subtasks }]
    },
    tree = { id: "1", tag: "pending", subtasks: [ { id: "2", tag: "pending", subtasks: [] }, { id: "3", tag: "in progress", subtasks: [{ id: "4", tag: "pending", subtasks: [{ id: "6", tag: "in progress", subtasks: [{ id: "10", tag: "pending", subtasks: [{ id: "11", tag: "complete", subtasks: [] }] }] }, { id: "7", tag: "complete", subtasks: [] }] }, { id: "5", tag: "pending", subtasks: [] }] }, { id: "4", tag: "complete", subtasks: [] }] },
    result = remove('in progress')(tree);
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 按预期工作,感谢您的友好沟通! :)
猜你喜欢
  • 2022-01-23
  • 2010-11-17
  • 2014-01-29
  • 2014-07-04
  • 2017-12-30
  • 2015-06-29
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
相关资源
最近更新 更多