在打字稿中创建带有对象数组的模型

Creating a model with object array in typescript

我正在尝试将基于 url 字符串的递归模型构建到类似树的视图中。我是 typescript 的新手,欢迎提出任何想法,谢谢。

//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 路径的树状结构。提前致谢。

您可以将字符串数组缩减为想要的结果:

 function buildTree(path: string): Node {
   return path.split("\").reduceRight((child, name) => ([{ name, child }], [])[0];
 }