Search code examples
javascriptarraystypescriptnodesparent-child

Creating a model with object array in typescript


I am trying to build a recursive model based on url strings in to a tree like view. I am very new to typescript, any thoughts are appreciated, thanks.

//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
  }
});

}

Expected result is tree like structure based on the url path provided. Thanks in advance.


Solution

  • You could just reduce the array of strings to the wanted result:

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