【问题标题】:How to modify tree object by property?如何按属性修改树对象?
【发布时间】:2021-05-15 10:16:48
【问题描述】:

我有一个对象类型:

export interface TreeNode extends ITreeNode {
   name: string,
   children:  TreeNode[],
   show?: boolean;
}

我需要通过属性show 减少这个对象并返回一个新树,其中showtrueundefined

我试过这个:

  function prepareNodes(source: TreeNode) {
        if (source.show!== undefined || source.show == false) delete source;
      if (source.children) {
        source.children.forEach((child: TreeNode) => {
          this.prepareNodes(child);
        });
      }
  }

我也试过了:

function prepareNodes(source: any) {
      if (source.show !== undefined && source.show === false) source = null;
      if (source.children) {
        source.children = source.children.filter((child: any) => child.show== undefined || child.show === true);
        source.children.forEach((child: any) => prepareNodes(child));
      }
  }

【问题讨论】:

标签: javascript typescript


【解决方案1】:

目前我的假设是您想要生成一个新树,其中仅包含原始树的那些节点,其中该节点的 show 属性为 trueundefined 以及所有祖先节点时间>。因此,如果show 在任何节点上为假,则输出树将不包含该节点或该节点的任何子树。

我还假设根节点有可能拥有showfalse,在这种情况下,整个树可能会以undefined 结束。不能设置修改对象成为undefined;您可以更改其内容,但不能删除它。所以我不会介绍任何试图修改原始树的东西。我不会碰原来的树。相反,我将生成一棵全新的树。

这里是:

const defined = <T,>(x: T | undefined): x is T => typeof x !== "undefined";

function filterTree(source: TreeNode): TreeNode | undefined {
  if (source.show === false) return;
  return {
    name: source.name,
    show: source.show,
    children: source.children.map(filterTree).filter(defined)
  }
}

如果参数节点的show 属性正好是false(而不是undefined),则filterTree() 函数将返回undefined。否则,它会生成一个具有相同nameshow 的新节点,其children 属性是您在每个原始节点的children 上调用filterTree()(递归)然后@ 987654343@ 出任何undefined 节点。

我正在使用名为defineduser-defined type guard 函数让编译器知道filtering 采用TreeNode | undefined 数组并生成TreeNode 数组,从而消除任何undefined 条目。

希望这能满足您的用例;请根据您拥有的任何数据进行测试并检查,因为不幸的是问题不包括此类数据。

Playground link to code

【讨论】:

  • 我可以用这个吗:return { ...source, children: source.children.map(filterTree).filter(defined) }
  • 可以,如果你愿意的话。
  • 如何从打字稿游乐场发布链接?太长了
  • 你想在哪里发布?您可以使用链接语法[text](url) 将其放入您的问题中。或者,如果您在 Playground 上安装 Link Shortener 插件,您可以为它们生成短链接,但我不知道如何通过 Internet 引导您完成该过程。
  • 看看它不适用于财产登记:stackblitz.com/edit/xy4wiq?file=index.ts
猜你喜欢
  • 2020-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 2011-08-31
相关资源
最近更新 更多