將有id和父級id的正常json數組改變為有children內嵌欄位的方法(俄羅斯套娃,可用於樹形控制項和樹形表格的生成,純js原生代碼,不需要其它依賴) ...
將有id和父級id的正常json數組改變為有children內嵌欄位的方法(俄羅斯套娃,可用於樹形控制項和樹形表格的生成,純js原生代碼,不需要其它依賴)
treeDataFormat(data, idField, parIdField, textField, openClose, rootId) { idField = idField || "id";//目標依據id parIdField = parIdField || "parent_id";//父級id textField = textField || "name";//文本欄位 rootId = rootId || 0; if (data && data.length > 0) { var dataMapping = {}; for (var i = 0; i < data.length; i++) { // dataMapping[data[i][idField]] = $.extend({}, data[i]); dataMapping[data[i][idField]] = data[i]; // dataMapping[data[i][idField]].children = []; dataMapping[data[i][idField]].text = dataMapping[data[i][idField]][textField]; dataMapping[data[i][idField]].state = openClose || "open"; } //構造上下級關係 for (var i = 0; i < data.length; i++) { var tempData = data[i]; if (tempData[parIdField] && dataMapping[tempData[parIdField]]) { dataMapping[tempData[parIdField]].children = dataMapping[tempData[parIdField]].children || []; dataMapping[tempData[parIdField]].children.push(dataMapping[tempData[idField]]); } } var treeArray = []; for (var key in dataMapping) { if (dataMapping[key].child_count != null || dataMapping[key].child_count != undefined) { //查詢出已明確定義子節點的數目 if (dataMapping[key].child_count > 0) { //有子節點 if (!dataMapping[key].children || dataMapping[key].children.length == 0) { dataMapping[key].state = "closed"; } else { dataMapping[key].state = "open"; } } else { //無子節點 dataMapping[key].state = "open"; } } else { if (!dataMapping[key].children || dataMapping[key].children.length == 0) { dataMapping[key].state = "open"; } } if (dataMapping[rootId]) {} else { if (dataMapping[key][parIdField] == rootId) { treeArray.push(dataMapping[key]); } } } if (dataMapping[rootId]) { treeArray.push(dataMapping[rootId]); } return treeArray; } return []; };