【问题标题】:Typescript get array of all children and grandchildren id's from parent id打字稿从父ID中获取所有子孙ID的数组
【发布时间】:2022-01-04 18:38:37
【问题描述】:

假设我有一个显示分层数据的对象数组:

const data = [
  { groupId: 1, parentGroupId: null },
  { groupId: 2, parentGroupId: 1 },
  { groupId: 3, parentGroupId: 1 },
  { groupId: 4, parentGroupId: null },
  { groupId: 5, parentGroupId: 99 },
  { groupId: 6, parentGroupId: 2 },
  { groupId: 7, parentGroupId: 6 },
  { groupId: 8, parentGroupId: 4 }];

如何编写一个递归打字稿函数,该函数接受 parentGroupId 参数并递归返回一个 groupId 数组,包括它自己的 groupId 和它的所有子代、孙代、曾孙代等的 groupId。

即。该函数应返回:

[1,2,3,6,7]

到目前为止,我有一个返回父级及其子级的函数,但我缺少递归部分以包括孙子、曾孙等。

 const data = [
          { groupId: 1, parentGroupId: null },
          { groupId: 2, parentGroupId: 1 },
          { groupId: 3, parentGroupId: 1 },
          { groupId: 4, parentGroupId: null },
          { groupId: 5, parentGroupId: 99 },
          { groupId: 6, parentGroupId: 2 },
          { groupId: 7, parentGroupId: 6 },
          { groupId: 8, parentGroupId: 4 }];
          
    function getChildIds(arr, parentGroupId) {
      return arr.reduce(function (ret, item) {
        if (item.parentGroupId == parentGroupId || item.groupId == parentGroupId) {
          ret = ret.concat(item.groupId);
        }
        return ret;
      }, []);
    }

    console.log(getChildIds(data, 1));

【问题讨论】:

    标签: typescript recursion parent-child hierarchical


    【解决方案1】:

    我最终选择了这个功能:

    function getChildIds(arr: any[], parentGroupId: number) {
      return arr.reduce(function (ret: any[], item: any) {
        if (item.parentGroupId == parentGroupId) {
          ret = ret.concat(item.groupId, getChildIds(arr, item.groupId));
        }
        return ret;
      }, []);
    }
    

    获取除原始父 ID 之外的每个 ID,然后我将其推送到数组

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2018-04-19
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多