我正在尝试基于URL字符串在树状视图中构建递归模型。我对打字稿非常陌生,感谢您的任何感激。
//node.ts interface
export interface Node {
name: string;
child: Node[];
}
//ObjectModel.ts
export class ObjectModel {
constructor(public parentNodes?: Node[]) { }
createObjectModel(path: string): ObjectModel {
//path = "one\two\three"
const nodeArr = path.split('\\');
//["one", "two", "three"]
const obj = nodeArr.reduce((o, key) => Object.assign(o, {[key]: nodeArr[0]}), {});
console.log(obj);
//{one: "one", two: "one", three: "one"}
return _.map(nodeArr, (node: Node) => {
return {
parentNodes: bomNode
}
});
}
预期结果是基于提供的url路径的树状结构。预先感谢。
答案 0 :(得分:0)
您可以将字符串数组简化为所需的结果:
function buildTree(path: string): Node {
return path.split("\\").reduceRight((child, name) => ([{ name, child }], [])[0];
}