如何在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
}));
但是孩子们没有遵循相同的形状。
答案 0 :(得分:1)
答案 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);