0

我正在从 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获得“可折叠力布局”效果

但我想在第一次加载时只加载第一个子元素。

就我而言

  • First root----->abcd First child---->Modules Second Child--->Features

我正在使用 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 的新手,对此有点困惑。

4

2 回答 2

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;
}
于 2013-08-05T16:03:30.393 回答
0

不要使用递归:

var node=[]
root.children.forEach(function(d){ node.push(d.children[0])})
console.log(node)

jsfiddl:http: //jsfiddle.net/nCLX9/

于 2013-08-05T11:13:36.360 回答