python画父子关系图_将有父子关系的一维数组转换成树形结构(多维)数据
先來個函數注釋 :
/**
* 將有父子關系的一維數組轉換成樹形結構(多維)數據
* console.log(JSON.stringify(setTreeData(data), null, 2));
* ============================================
* @param {*Array} data 需要遍歷的一維數組
*/
再來具體的代碼 :
function fnSetTreeData(data) {
var data = [...data];
var tree = data.filter((father) => {
var branchArr = data.filter((child) => {
if (father.id == child.parentId) child._hasParent = true;
return father.id == child.parentId;
// MARK 為什么這樣寫就報錯 ?
// if (father.id == child.parentId) child._hasParent = true;
// return child._hasParent
});
if (branchArr.length > 0) father.children = branchArr;
return !father._hasParent;
});
// MARK 為什么在這里還得加一個過濾
tree = tree.filter((item) => {
return !item._hasParent;
})
return tree
}
console.log(JSON.stringify(fnSetTreeData(data), null, 2));
至于怎么解決 循環(huán)引用 的問題, 先用 sort 給數組排序后, 再在每次filter 中 計數++如何 ?
得給一個測試數據 :
var data = [
{ id: 40, parentId: 31, note: "的薩達是" },
{ id: 20, parentId: 11, note: "的薩達是" },
{ id: 22, parentId: 20, note: "dsadas" },
{ id: 12, parentId: null, note: "dsadasad薩達s" },
{ id: 11, parentId: undefined, note: "dqwds" },
{ id: 24, parentId: 22, note: "搜索" },
{ id: 34, parentId: 22, note: "搜索" }
];
總結
以上是生活随笔為你收集整理的python画父子关系图_将有父子关系的一维数组转换成树形结构(多维)数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 豫剧演员雪天为3名观众表演2小时 获网友
- 下一篇: python中socket模块常用吗_p