我刚刚找到了一个名为“ stringify”的函数,它看起来像是一种将平面数据转换为Json样式的惊人方法。
如果这是真的,那将为我节省使用ASP / SQL进行递归编程的时间。
我的代码在这里:Original code
我正在尝试用数据创建相同的效果,我已经在这里进行了研究,您可以运行它并提供相同的结构。
<script>
var data = [
{ "name" : "A", "parent":"null" },
{ "name" : "J", "parent":"A"},
{ "name" : "I", "parent":"A" },
{ "name" : "G", "parent":"A" },
{ "name" : "H", "parent":"A" },
{ "name" : "Cr", "parent":"B" },
{ "name" : "D", "parent":"Cr" },
{ "name" : "E", "parent":"Cr" },
{ "name" : "H", "parent":"A" },
{ "name" : "F", "parent":"Cr"},
{ "name" : "B", "parent":"A" }
];
// create a name: node map
var dataMap = data.reduce(function(map, node) {
map[node.name] = node;
return map;
}, {});
// create the tree
var tree = [];
data.forEach(function(node) {
// add to parent
var parent = dataMap[node.parent];
if (parent) {
// create child
(parent.children || (parent.children = []))
// add node
.push(node);
} else {
// null or missing
tree.push(node);
}
});
d3.select('body').append('pre').text(JSON.stringify(tree, null, ' '));
我现在在将两者整合在一起时遇到问题吗?
这可能真的很容易-但是在喝完咖啡后凝视并重新编写。
任何人都有提示吗?我们将不胜感激,并感谢您阅读本文-我不介意大家GURU是否修改或重新创建了我已有的代码。
答案 0 :(得分:0)
已解决!
经过几次表述后,我对功能进行了排序。
这是一份科学怪人的工作,但是却行得通-直到我学到更多令我满意的东西为止。
使用行
JSON.stringify(tree, null, ' ')
我直接替换了var n = ...字符串。