js怎么动态给树形结构添加子节点?

例如有一个初始对象:
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)
  }
阅读 583
评论
    4 个回答

    可以用递归实现:

    function generateChildren(x, obj = {}) {
      if (x === 0) {
        return {}
      } else if (x === 1) {
        return {children: [{}]}
      } else {
        return {children: [generateChildren(obj, x - 1)]}
      }
    }
      • 580

      你这样做有什么意义吗?

      function generateChildren(obj, x) {
        while (x--) {
          obj.children = [{}];
          obj = obj.children[0];
        }
      }
        let obj: any = {};
        generateChildren(obj, 10)
        function generateChildren(obj: any, x: number) {
            for (let i = 0; i < x; i++) {
                addChildren(obj)
            }
        }
        
        function addChildren(obj: any) {
            if (!obj.children) {
                obj.children = [];
                return;
            }
            if(!obj.children.children){
                obj.children.children = [];
                return;
            }else{
                if(obj.children.children){
                    addChildren(obj.children.children);
                }
            }   
        }
          • 4
          • 新人请关照
          var testObj = {}
          var x = 3
          for (let i = 0; i < x; i++) {
              var cObj = {children: {}}
              testObj['children'] = cObj
          }
          console.log('testObj')
          console.log(testObj)

          这样不香吗

            撰写回答

            登录后参与交流、获取后续更新提醒