在Javascript中递归创建子属性

时间:2018-04-18 16:24:31

标签: javascript dictionary children

我正在尝试根据传递的参数n创建子项深度。 基本上如果n是4,那么结果对象应该是 parent.children.children.children.children

到目前为止,我已经提出了这个问题:

parent = {}

function makechildren( current, depth ){
  current['children']={}
  while (depth>0){       {
    str = JSON.stringify(current)
    return makechildren(current, depth-1)
  }
}
}
makechildren(parent, 4)

1 个答案:

答案 0 :(得分:2)

我测试了这段代码并且它可以正常工作

parent={};
var obj;
function makechildren( current, depth){
  if(depth>0) 
  {  
    current = JSON.parse(JSON.stringify(current).replace('{}','{"children":{}}'))
    makechildren(current, depth-1);
  }else{
    obj = current;
    return ;
  }

}
console.log(obj)
相关问题