js把樹形數據轉成扁平數據


我就直接上代碼了都是實際項目里面用到的

1.假設這個json就已經是樹型結構數據了(如果不知道怎么實現樹型結構數據請看我另一篇博客
var compressedArr=afcommon.treeDataToCompressed(json);

/*******************************JS封裝好的方法*********************************************/

var afcommon=(function ($) {
var prefix="|—";
let compressedData=[];// 用於存儲遞歸結果(扁平數據)
return {

/**
* 把扁平數據轉成樹型結構數據(可以實現無限層級樹形數據結構,只適用於單個表的數據)
* @param source
* @param id
* @param parentId
* @param children
*/
treeDataformat : function(source, id, parentId, children){
let cloneData = JSON.parse(JSON.stringify(source)); // 對源數據深度克隆
return cloneData.filter(father=>{ // 循環所有項,並添加children屬性
let branchArr = cloneData.filter(child => father[id] == child[parentId]); // 返回每一項的子級數組
branchArr.length>0 ? father[children] = branchArr : '' //給父級添加一個children屬性,並賦值
return father[parentId] == 0 // 如果第一層不是parentId=0,請自行修改
})
},
/**
* 把樹型結構數據轉成扁平數據(跟treeDataformat方法相反)
* @param source
*/
treeDataToCompressed :function (source) {
for(let i in source) {
compressedData.push(source[i]);
source[i].children && source[i].children.length>0 ? this.treeDataToCompressed(source[i].children) : ""// 子級遞歸
}
return compressedData;
},
/**
* 遞歸生成 樹下拉菜單
* @param JsonTree 此參數已經是樹型結構的數據了 如:JsonTree[{"id": "0","value":"測試","children": []}]
* @param typeId
* @param name
* @returns {string}
*/
creatSelectTree : function(JsonTree,typeId,name){//js腳本,遞歸生成 樹下拉菜單
var option="";
for(var i=0;i<JsonTree.length;i++){
if(JsonTree[i].children!= undefined && JsonTree[i].children.length>0){//如果有子集
option+="<option value='"+JsonTree[i][typeId]+"'>"+prefix+JsonTree[i][name]+"</option>";
prefix+="|—";//前綴符號加一個符號
option+=this.creatSelectTree(JsonTree[i].children,typeId,name);//遞歸調用子集
prefix=prefix.slice(0,prefix.length-2);//每次遞歸結束返回上級時,前綴符號需要減一個符號
}else{//沒有子集直接顯示
option+="<option value='"+JsonTree[i][typeId]+"'>"+prefix+JsonTree[i][name]+"</option>";
}
}
return option;//返回最終html結果
},
/**
* 適用於layer.confirm 動態改變title 多語言切換
* layer.confirm(msg,{titel:'Message'},{btn: ['確定','取消']}, function () {},function () {}) (這樣寫改變title 好像會對后面的回調函數有影響,不信你試試)
* @param title
* @param index
*/
changeLayerTitle: function (title,index) {
return layer.title(title, index)
},
}
})(jQuery);

測試結構:

好的東西就要懂得分享,推薦一個寫的好的博客一個字來形容———厲害!

https://blog.csdn.net/Mr_JavaScript/article/details/102833991


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM