为新的输出对象创建递归函数

问题描述 投票:0回答:1

我得到以下结果(来自外部 API 的响应):

Results = [
  {
    "ID": "2",
    "Name": "Home",
    "ParentID": "1",
    "Path": "/home"
  },
  {
    "ID": "3",
    "Name": "Contacts",
    "ParentID": "1",
    "Path": "/contacts"
  },
  {
    "ID": "4",
    "Name": "Help",
    "ParentID": "3",
    "Path": "/contacts/help"
  },
  {
    "ID": "5",
    "Name": "Form",
    "ParentID": "4",
    "Path": "/contacts/help/form"
  },
  {
    "ID": "6",
    "Name": "Information",
    "ParentID": "4",
    "Path": "/contacts/help/information"
  }
]

ID财产始终是唯一的;

ParentID属性是对父级的引用(ID)(ParentID=1是源“/”)。每个对象都有一个ParentID

我需要创建一个具有以下响应的 HTTP 方法(在 C# 中):

Output = [
  {
    "Name": "Home",
    "Path": "/home",
    "Childrens": []
  },
  {
    "Name": "Contacts",
    "Path": "/contacts",
    "Childrens": [
      {
        "Name": "Help",
        "Path": "/contacts/help",
        "Childrens": [
          {
            "Name": "Form",
            "Path": "/contacts/help/form",
            "Childrens": []
          },
          {
            "Name": "Information",
            "Path": "/contacts/help/information",
            "Childrens": []
          }
        ]
      }
    ]
  }
]

我该怎么做?我可以做一个递归函数吗?

附注如果您只给我建议和提示,我将不胜感激。

(已编辑)

c# arrays algorithm recursion return
1个回答
0
投票

我在 python 中用两步完成了这个(抱歉不知道 csharp 语法):

  • 创建哪些节点是哪些其他节点的子节点的映射
  • 使用更新的格式构建一个新节点并递归构建其子节点

这是示例代码:

def recAdd(vck, objs, target):
    children = []
    for x in vck[target]:
        children.append(recAdd(vck, objs, x))
    obj = {
            "Name" : objs[target]["Name"],
            "Path" : objs[target]["Path"],
            "Children" : children
            }
    return obj

def convert(objs):
    ids = {}
    for obj in objs:
        ids[obj["ID"]] = obj

    valueIsChildOfKey= {}
    for k,v in ids.items():
        if k not in valueIsChildOfKey.keys():
            valueIsChildOfKey[k] = []
        if v["ParentID"] in valueIsChildOfKey.keys():
            valueIsChildOfKey[v["ParentID"]].append(k)
        else:
            valueIsChildOfKey[v["ParentID"]] = [k]
    out = []
    for x in valueIsChildOfKey["1"]:
        out.append(recAdd(valueIsChildOfKey, ids, x))

    return out
if __name__ == "__main__":
    Results = [ {"ID": "2","Name": "Home","ParentID": "1","Path": "/home"}, { "ID": "3", "Name": "Contacts", "ParentID": "1", "Path": "/contacts" }, { "ID": "4", "Name": "Help", "ParentID": "3", "Path": "/contacts/help" }, { "ID": "5", "Name": "Form", "ParentID": "4", "Path": "/contacts/help/form" }, { "ID": "6", "Name": "Information", "ParentID": "4", "Path": "/contacts/help/information" } ]
    print(convert(Results))
© www.soinside.com 2019 - 2024. All rights reserved.