我是D3的新手。我使用的是d3.jd版本3。我有以下类型的JSON:
[
{
"health": "OK",
"name": "new A",
"index": "A"
},
{
"health": "SEVERE",
"name": "new AB",
"index": "A > B"
},
{
"health": "OK",
"name": "new ABC",
"index": "A > B > C"
},
{
"health": "OK",
"name": "new ADE",
"index": "A > D > E"
},
{
"health": "SEVERE",
"name": "new AD",
"index": "A > D"
}
]我想从上面的JSON创建以下父子嵌套数据:
[
{
"health": "OK",
"name": "new A",
"index": "A",
"children": [
{
"health": "SEVERE",
"name": "new AB",
"index": "A > B",
"children": [
{
"health": "OK",
"name": "new ABC",
"index": "A > B > C"
}
]
},
{
"health": "SEVERE",
"name": "new AD",
"index": "A > D",
"children": [
{
"health": "OK",
"name": "new ADE",
"index": "A > D > E"
}
]
}
]
}
]我想通过索引创建父子数据。因此,如果索引是"A > B“,"A”是父级,"B“是子级。
这只是我没有的样本数据。大量的数据。所以,想要提高性能。
是否可以使用d3或jquery来创建嵌套的父子JSON形式的object数组?
发布于 2017-07-06 13:40:25
我已经做到了。为此,我需要添加父id。
var data = [
{
"health": "OK",
"name": "new A",
"index": "A"
},
{
"health": "SEVERE",
"name": "new AB",
"index": "A > B"
},
{
"health": "OK",
"name": "new ABC",
"index": "A > B > C"
},
{
"health": "OK",
"name": "new ADE",
"index": "A > D > E"
},
{
"health": "SEVERE",
"name": "new AD",
"index": "A > D"
}
]
function fnGetParentID(index) {
var indexArr = index.split(' > ');
var parentIndex = '';
if(indexArr.length !== 1){
parentIndex = index.replace(" > " + indexArr[indexArr.length - 1], '')
}
return parentIndex;
};
function fnCreateStrunture(f) {
return f.sort(function (a, b) {
return a.index.length < b.index.length ? 1 : a.index.length == b.index.length ? a.index < b.index ? -1 : 1 : -1;
}).reduce(function (p, c, i, a) {
c.ParentID = fnGetParentID(c.index);
var parent = !!c.ParentID && a.find(function (e) {
return e.index === c.ParentID;
});
? parent.children && parent.children.push(c) || (parent.children = [c]) : p.push(c);
return p;
}, []);
};
var nestedJson = fnCreateStrunture(data);
document.getElementById("nested").innerHTML = JSON.stringify(nestedJson, undefined, 2);<pre id="nested"></pre>
https://stackoverflow.com/questions/44918298
复制相似问题