javascript - 在打字稿中使用对象数组创建模型
问题描述
我正在尝试将基于 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 路径的树状结构。提前致谢。
解决方案
您可以将字符串数组减少为想要的结果:
function buildTree(path: string): Node {
return path.split("\\").reduceRight((child, name) => ([{ name, child }], [])[0];
}
推荐阅读
- sql - 检查相同的 id 是否具有确定的条件
- angularjs - 如何通过索引访问数组中的数据以获取 AngularJs 中的重复项
- java - 卡夫卡和 OpenJDK
- azure - Azure 函数 - 事件中心触发器已停止
- c# - 如何动态创建 XML 文件?
- laravel - Laravel Model::find() 自动按 id 对结果进行排序,如何停止呢?
- google-apps-script - 如何在 GAS 中运行/调试私有函数?
- python - settimeout() 忽略 Try/Except 的异常 - Python
- scrapy - 将项目(或其他变量)传递给 scrapy 的中间件(或其他模块)。
- build - Thinlto 的并发性在并行构建系统中有用吗?