gpt4 book ai didi

javascript - 如何编写递归 d3.js 代码来处理嵌套数据结构?

转载 作者:数据小太阳 更新时间:2023-10-29 05:16:11 25 4
gpt4 key购买 nike

我有 functional programming 的背景并在原则上理解递归,但我似乎无法将这些知识转化为 D3.js环境。

我下面有一个 hello world 脚本,它试图简单地打印嵌套数据结构的内容。根据其他线程的建议,我可以使用 .filter 仅返回节点,但如何继续此示例以递归打印嵌套项?

<!DOCYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="d3.v3.js"></script>

<script>
function draw(data)
{
"use strict";

d3.select("body")
.selectAll("p")
.data(data)
.enter()
.append("p")
.text(function(d) {
if (d instanceof Array) {
return "WHAT DO I PUT HERE?";
}
else {
return d;
};
});
}
</script>
</head>

<body>
Hello world

<script>
draw([1, [2, [1, 2, 3, 4] ], 3, 4, 5]);
</script>
</body>
</html>

最佳答案

您需要一个根特征,然后是一个递归函数来填充它。

function makeNestedListItems (parentLists) {
var item = parentLists.append('li')
.text(function (d) { return d.txt; });
var children = parentLists.selectAll('ul')
.data(function (d) {
return d.children
})
.enter().append('ul');
if (!children.empty()) {
makeNestedListItems(children);
}
}
var data = {
txt: 'root',
children: [{
txt: "a",
children: [{
txt: "aa",
children: [{
txt: "aaa",
children: []
}, {
txt: "aab",
children: []
}
]
}, {
txt: "ab",
children: []
}
]
}, {
txt: "b",
children: [{
txt: "ba",
children: []
}, {
txt: "bb",
children: []
}, {
txt: "bc",
children: []
}
]
}, {
txt: "c",
children: []
}
]
};
var rootList = d3.select('body').selectAll('ul').data([data])
.enter().append('ul');
makeNestedListItems(rootList);

哪个应该产生

    • 一个
      • aa
        • 啊啊
        • aab
      • ab
    • b
      • ba
      • bb
      • 公元前
    • c

关于javascript - 如何编写递归 d3.js 代码来处理嵌套数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14380520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com