我正在尝试将仅由键组成的嵌套对象转换为由这些键引用的数据组成的嵌套数组,以便它符合气泡图的d3.js模式。
嵌套对象如下所示:
{
"f5eade20-110f-11e5-9c61-33ffcb46c0ef":{
},
"ff4477e0-6a2c-11e4-afd1-83393415d9ef":{
"0153f8b0-265a-11e4-8585-9b3341099b01":{
"0159c510-265a-11e4-8585-9b3341099b01":{
"11615f20-fbf9-11e4-b3d5-771ea6705f5b":{
}
},
"83180020-f504-11e4-917c-b121cbe20dd2":{
},
"ddc13830-fa76-11e4-a09d-430b71e0fc3f":{
}
},
"022bbb10-265a-11e4-8585-9b3341099b01":{
"7daa5900-fbf6-11e4-bdf8-fdcd51308cde":{
},
"cbbad030-6c0d-11e4-b161-d9c9c481a5bc":{
"3990b5c0-f53e-11e4-917c-b121cbe20dd2":{
}
},
"7347bc80-38fd-11e4-a2b7-d7a74243b515":{
"98b00f90-fb53-11e4-bd16-359096879648":{
}
},
"a7dd2b50-36ce-11e4-b2d6-85c2a0c3f504":{
"7347bc80-38fd-11e4-a2b7-d7a74243b515":{
"f823a7b0-f753-11e4-b9ef-1bae8d43be66":{
}
}
}
}
}
}
在另一个数组中查找这些键以获取它们的值(name
属性)后,转换需要看起来像d3.js才能读取它:
{
"name":"Parent 1",
"children":[
{
"name":"Child 1",
"children":[
{
"name":"Child 1",
"children":null
},
{
"name":"Grandchild 1.1",
"children":null
},
{
"name":"Grandchild 1.2",
"children":null
}
]
},
{
"name":"Child 2",
"children":[
{
"name":"Child 2",
"children":null
},
{
"name":"Grandchild 2.1",
"children":null
},
{
"name":"Grandchild 2.2",
"children":null
}
]
},
{
"name":"Child 3",
"children":[
{
"name":"Child 3",
"children":null
},
{
"name":"Grandchild 3.1",
"children":null
},
{
"name":"Grandchild 3.2",
"children":null
}
]
},
{
"name":"Child 4",
"children":[
{
"name":"Child 4",
"children":null
},
{
"name":"Grandchild 4.1",
"children":null
},
{
"name":"Grandchild 4.2",
"children":null
}
]
}
]
}
我试图弄清楚如何做到这一点时,我的头靠在墙上,并感激任何帮助。
答案 0 :(得分:2)
您想为此使用递归函数。以下是一些帮助您入门的基本内容。
var obj = {
"f5eade20-110f-11e5-9c61-33ffcb46c0ef":{
},
"ff4477e0-6a2c-11e4-afd1-83393415d9ef":{
"0153f8b0-265a-11e4-8585-9b3341099b01":{
"0159c510-265a-11e4-8585-9b3341099b01":{
"11615f20-fbf9-11e4-b3d5-771ea6705f5b":{
}
},
"83180020-f504-11e4-917c-b121cbe20dd2":{
},
"ddc13830-fa76-11e4-a09d-430b71e0fc3f":{
}
},
"022bbb10-265a-11e4-8585-9b3341099b01":{
"7daa5900-fbf6-11e4-bdf8-fdcd51308cde":{
},
"cbbad030-6c0d-11e4-b161-d9c9c481a5bc":{
"3990b5c0-f53e-11e4-917c-b121cbe20dd2":{
}
},
"7347bc80-38fd-11e4-a2b7-d7a74243b515":{
"98b00f90-fb53-11e4-bd16-359096879648":{
}
},
"a7dd2b50-36ce-11e4-b2d6-85c2a0c3f504":{
"7347bc80-38fd-11e4-a2b7-d7a74243b515":{
"f823a7b0-f753-11e4-b9ef-1bae8d43be66":{
}
}
}
}
}
};
var final_obj = Convert(obj);
function Convert(obj_to_convert) {
var new_obj = [];
for (var i in obj_to_convert) {
new_obj.push({
name: i,
children: Convert(obj_to_convert[i])
});
}
return new_obj;
};
$('#results').text(JSON.stringify(final_obj, null, 4));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<pre id="results"></pre>