嗨,我一直在致力于将树转换为对象。我知道如何递归获取整个树,但是我不知道将json ['name']和json ['children']放置在何处,并达到预期的结果。有没有人可以给我提示?
谢谢您的帮助。
# Here is the tree structure that is created by tree-model.min.js
#Input:
/*
tree = Node{
config: {childrenPropertyName: "children", modelComparatorFn: undefined}
model: {"name": str_1, "children": [Node, ..., Node]}
children: [Node, Node, ..., Node]
}
*/
#Expected outcome:
/*
{name: str_1, children: [
{name: str_2, children: [...]},
{name: str_3, children: [...]}
]}
*/
# Here is what I have tried
function treeToJSON(tree, json){
console.log(tree.model.name)
console.log(json)
if(tree.hasChildren()){
json['name'] = tree.model.name;
(tree.children).forEach(function(_tree){
if(!json['children']){
json['children'] = []
}
json['children'].push({'name': _tree.model.name})
return treeToJSON(_tree, json)
})
}
else{
json['name'] =tree.model.name
return json
}
}
treeToJSON(tree, {})