例如有一个初始对象:let obj = {}
现在有一个变量x,int类型,通过循环i的值来新增obj的children,如:for (let i = 0; i < x; i++) {}
i=0时,obj为{}
i=1时,obj为{children: [{}]}
i=2时,obj为{children: [{children:[{}]}]}
i=3时,obj为{children: [{children:[{children:[{}]}]}]}
...
以此类推,应该如何处理?
modify date: 2019-12-5
原需求是根据层级数来生成对应层级的树结构,并在末级节点添加指定的对象,现在问题已经解决,非常感谢各位大佬提供的思路,让我获益匪浅。一下是我的实现方式,分享出来:
createTree (level) {
let node = []
for (let i = level; i > 0; i--) {
// 将各级节点展开在node中
node[i - 1] = function (num) {
return function (num) {
// 子节点
let children = [{
title: '',
levelMax: i
}]
// 末级节点增加考核要点
if (i === level) {
// 考核要点
let _childRule = [{
dataCollectionOrgId: "",
dataCollectionOrgName: "",
lableType: 0,
lableTypeName: "",
perDesc: "",
score: 0,
scoreMethod: 0
}]
children[0] = { ...children[0], childRule: _childRule }
console.log('last node:', children)
}
return children[0]
}(i)
} (i)
// 排除i等于level的情况,node中不存在这个位置
if (i > 0 && i <= level - 1) {
// 从node末尾开始向前合并子节点
node[i - 1]['children'] = { ...node[i - 1][0], ...node[i] }
}
}
// 保留树形结构node[0]
node.splice(1)
this.$set(this.templateTree, 0, node[0])
console.log('templateTree: ', this.templateTree)
}
可以用递归实现: