我正在从mongodb .find()中检索记录并尝试使用d3v4 .stratify()来嵌套它们。不幸的是,我收到了错误
错误:含糊不清:产品系列1
我假设我误解了API documentation。
虽然问题似乎接近this post,但我认为它并不完全相同。但是,我试图获得IS like this的结果。
有人可以帮我理解如何正确使用.stratify()吗?或建议一个更简单的方法来做到这一点?
我的结果集(mongodb_data
)不大(可能约有2500种产品)。
我的公寓mongodb_data
看起来像这样,
[
{
"name": "Product Line 1",
"reference": "product 1.A identifier"
},
{
"name": "Product Line 1",
"reference": "product 1.B identifier"
},
{
"name": "Product Line 2",
"reference": "product 2.A identifier"
},
{
"name": "Product Line 2",
"reference": "product 2.B identifier"
}
];
所需的分层/嵌套数据需要如下所示
{
"name": "Master Product Catalog",
"children": [
{
"name": "Product Line 1",
"children": [
{ "name": "product 1.A identifier" },
{ "name": "product 1.B identifier" }
]
},
{ "name": "Product Line 2",
"children": [
{ "name": "product 2.A identifier" },
{ "name": "product 2.B identifier" }
]
}
]
}
我一直在使用API文档中的示例,如下所示,
var stratdata = d3.stratify()
.id(function(d) { return d.name; })
.parentId(function(d) { return d.name; })
(mongodb_data);
答案 0 :(得分:0)
您的单位数据不代表分层结构。它没有回答“产品线1”或“产品线2”父母的问题?此外,您的name
属性不包含父信息和子信息(引用是父项,名称是子项)。 d3.stratify()
之前的数据应如下所示:
[{
"reference": "Master Product Catalog",
"name": "" //<-- has no parent
}, {
"reference": "Product Line 1",
"name": "Master Product Catalog" //<-- parent is master
}, {
"reference": "Product Line 2",
"name": "Master Product Catalog"
}, {
"name": "Product Line 1",
"reference": "product 1.A identifier"
}, {
"name": "Product Line 1",
"reference": "product 1.B identifier"
}, {
"name": "Product Line 2",
"reference": "product 2.A identifier"
}, {
"name": "Product Line 2",
"reference": "product 2.B identifier"
}];
运行代码:
<!DOCTYPE html>
<html>
<head>
<script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
var json = [{
"reference": "Master Product Catalog",
"name": ""
}, {
"reference": "Product Line 1",
"name": "Master Product Catalog"
}, {
"reference": "Product Line 2",
"name": "Master Product Catalog"
}, {
"name": "Product Line 1",
"reference": "product 1.A identifier"
}, {
"name": "Product Line 1",
"reference": "product 1.B identifier"
}, {
"name": "Product Line 2",
"reference": "product 2.A identifier"
}, {
"name": "Product Line 2",
"reference": "product 2.B identifier"
}];
var root = d3.stratify()
.id(function(d) {
return d.reference;
})
.parentId(function(d) {
return d.name;
})
(json);
console.log(root)
</script>
</body>
</html>