首页 > 解决方案 > 在打字稿中使用对象数组创建模型

问题描述

我正在尝试将基于 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 路径的树状结构。提前致谢。

标签: javascriptarraystypescriptnodesparent-child

解决方案


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

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

推荐阅读