我正在从mongodb .find()中检索记录,并尝试将它们与d3v4 .stratify()嵌套在一起。不幸的是,我遇到了错误
错误:模棱两可:产品线1
我想我误会了API documentation。
虽然问题似乎与this post接近,但我认为问题并不完全相同。但是,我要达到的结果是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);
最佳答案
您的平面数据不代表层次结构。它没有回答“产品线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="[email protected]" 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>