策略是根据你想要的创建一个新的空数据结构,然后通过遍历整个原始数据集来填充它。这是代码:
var data = [
{ "dep": "d1", "name": "name1", "size": "size1" },
{ "dep": "d1", "name": "name2", "size": "size2" },
{ "dep": "d2", "name": "name1", "size": "size3" },
{ "dep": "d2", "name": "name2", "size": "size4" }
]
var newData = {"name": "root", "children": {}}
data.forEach(function (d) {
if (typeof newData.children[d.dep] !== 'undefined') {
newData.children[d.dep].children.push(d)
} else {
newData.children[d.dep] = {"name": d.dep, "children": [d]}
}
})
newData.children = Object.keys(newData.children).map(function (key) {
return newData.children[key];
});
最后的赋值是将对象转换为数组。
这给出了所需的结果newData
:
{
"name": "root",
"children": [
{ "name": "d1",
"children": [
{ "dep": "d1", "name": "name1", "size": "size1" },
{ "dep": "d1", "name": "name2", "size": "size2" }
]
},
{ "name": "d2",
"children": [
{ "dep": "d2", "name": "name1", "size": "size3" },
{ "dep": "d2", "name": "name2", "size": "size4" }
]
}
]
}
jsFiddle:http: //jsfiddle.net/chrisJamesC/eB4jF/
注意:此方法不适用于嵌套结构。对嵌套结构执行此操作会更加困难,但您始终可以使用递归函数。
编辑:正如@imarane 在他的回答中所建议的,您可以使用d3.nest()这比我手工制作的解决方案要好得多。你可能会因此接受他的回答。通过玩它,甚至可以很容易地拥有多层嵌套:
var data = [
{ "dep": "d1", "name": "name1", "size": "size1" },
{ "dep": "d1", "name": "name2", "size": "size2" },
{ "dep": "d2", "name": "name1"},
{ "dep": "d2"}
]
var newData = {
"key":"root",
"children":
d3.nest()
.key(function(d){return d.dep})
.key(function(d){return d.name})
.key(function(d){return d.size})
.entries(data)
}
其中给出:
{"key":"root","children":[
{"key":"d1","values":[
{"key":"name2","values":[
{"dep":"d1","name":"name2","size":"size1"},
{"dep":"d1","name":"name2","size":"size2"}
]}
]},
{"key":"d2","values":[
{"key":"name1","values":[
{"dep":"d2","name":"name1"}
]},
{"key":"undefined","values":[
{"dep":"d2"}
]}
]}
]}
其中以下数据结构(我希望能更好地理解整点):
var data = [
{ "dep": "d1", "name": "name2", "size": "size1" },
{ "dep": "d1", "name": "name2", "size": "size2" },
{ "dep": "d2", "name": "name1"},
{ "dep": "d2"}
]
JsFiddle:http: //jsfiddle.net/chrisJamesC/eB4jF/2/
更多关于 Nest: http ://bl.ocks.org/phoebebright/raw/3176159/