我从json获取数据
{
"name": "abcd", "size": 150000,
"children": [
{
"name": "Modules", "size": 100000,
"children": [
{"name": "Audio Library", "size": 100000, "info": "hello", "image": "http://s3.amazonaws.com/web2tools-production/images/199/Google_logo.PNG"},
{"name": "CommentBox", "size": 100000, "info": "hi" },
{"name": "Localization", "size": 100000, "info": "hi there"}
]
},
{
"name": "Features", "size": 100000,
"children": [
{"name": "Rapid Development", "size": 100000, "info": "hello", "image": "http://s3.amazonaws.com/web2tools-production/images/199/Google_logo.PNG"},
{"name": "User friendly interface", "size": 100000, "info": "hi" },
{"name": "Highly Customizable", "size": 100000, "info": "hi there"},
{"name": "Full control", "size": 100000, "info": "hi" },
{"name": "Open Source", "size": 100000, "info": "hi there"}
]
}
]
}
现在我正在尝试使用d3.js获得“可折叠力布局”效果 作为http://bl.ocks.org/mbostock/1093130
但我想在第一次加载时只加载第一个子元素。
就我而言
我使用flatten函数从json获取所有节点
function flatten(root) {
var nodes = [], i = 0;
function recurse(node) {
if (node.children) node.children.forEach(recurse);
if (!node.id) node.id = ++i;
nodes.push(node);
}
recurse(root);
return nodes;
}
现在,我如何从此函数中获取第一个子元素。 我是d3.js的新手,对此有点困惑。
答案 0 :(得分:0)
不要使用递归:
var node=[]
root.children.forEach(function(d){ node.push(d.children[0])})
console.log(node)
jsfiddl:http://jsfiddle.net/nCLX9/
答案 1 :(得分:0)
如果您只想将顶级子元素作为特例,那么您是否只能访问root.children
?
如果要返回任意级别,可以为递归函数添加级别限制。像(未经测试)的东西:
function flatten(root, level) {
level = level !== undefined ? level : 1;
var nodes = [], i = 0;
function recurse(node, currentLevel) {
currentLevel !== undefined ? currentLevel : 1;
if (node.children && currentLevel < level) {
node.children.forEach(function(child) {
recurse(child, currentLevel+1);
});
}
if (!node.id) node.id = ++i;
nodes.push(node);
}
recurse(root);
return nodes;
}