如何将对象数组的树结构克隆到另一个对象,从而将属性更改为克隆对象?

时间:2020-10-14 15:53:56

标签: angular typescript primeng-tree

如何在TypeScript中将对象数组的树结构克隆到另一个对象上,而这些对象具有不同或更少的外观? 例如:

[
   {
      "name":"root_1",
      "extradata":"whatever",
      "anArray":[
         { "id":1, "value":"test" },
         { "id":1, "value":"test" }
      ],
      "anObject":{ "id":1, "value":"test" },
      "children":[
         {
            "name":"child_1",
            "extradata":"whatever",
            "anArray":[],
            "anObject":{},
            "children":[
               {
                  "name":"root_1",
                  "extradata":"whatever",
                  "anArray":[],
                  "anObject":{},
                  "children":[]
               },
               {
                  "name":"root_1",
                  "extradata":"whatever",
                  "anArray":[],
                  "anObject":{},
                  "children":[]
               }
            ]
         }
      ]
   },
   {
      "name":"root_2",
      "extradata":"whatever",
      "anArray":[],
      "anObject":{},
      "children":[]
   }
]

我需要它的一个克隆,但不是“属性”的“标签”,而是“ extradata” =“ key”,没有“ anArray”和“ anObject”。像这样:

[
   {
      "label":"root_1",
      "key":"whatever",
      "children":[
         {
            "label":"child_1",
            "key":"whatever",
            "children":[
               {
                  "label":"root_1",
                  "key":"whatever",
                  "children":[]
               },
               {
                  "label":"root_1",
                  "key":"whatever",
                  "children":[]
               }
            ]
         }
      ]
   },
   {
      "label":"root_2",
      "key":"whatever",
      "children":[]
   }
]

我需要克隆它,以便使用它作为primng树组件的数据格式。

我正在尝试类似的东西

this.myTree = tree.map((m, index) => Object.assign({}, {
                                label: m.name,
                                key: m.extradata,
                                children: m.children
                            }));

但是孩子们没有遵循相同的形状。

2 个答案:

答案 0 :(得分:1)

我不确定您是否可以使用第三方库-但是您听说过loadsh吗? 关于如何实现这一目标的例子很多(:

first example

second example

如果您无法使用它,我只需dive进入代码,看看他们是如何实现的(:

答案 1 :(得分:1)

我将通过首先为所讨论的输入和输出类型定义接口来做到这一点:

interface InputTree {
  name: string,
  extradata: string,
  anArray: any[],
  anObject: object,
  children: InputTree[]
}

interface OutputTree {
  label: string,
  key: string,
  children: OutputTree[];
}

根据您的定义,您的输入似乎是InputTree[],并且您想产生一个OutputTree[]。树是递归的,因此您应该编写一个在treeMap()上运行的InputTree[]函数,然后在数组中每个children的{​​{1}}上递归调用自身。像这样:

InputTree

您可以验证是否可以产生预期的输出:

const treeMap = (inputTree: InputTree[]): OutputTree[] => inputTree.map(t => ({
  label: t.name,
  key: t.extradata,
  children: treeMap(t.children)
}));

const actual = treeMap(tree);

Playground link to code