tree 長像:
匯入用的 csv:
a,,
,b,
,,d
,,,f
,,,,g
,c,
,,d
,e,
,f,
轉換 csv 為 json tree:
let csv_string = $('#treechart-tab-csv-textarea').val();
const lines = csv_string.split(/\r?\n/);
for(let i=0; i<lines.length; i++) {
const line = lines[i];
if(line.length) {
let title = "";
let lv = -1;
const columns = line.split(/,/);
for(let j=0; j<columns.length; j++) {
const column = columns[j];
if(column.length) {
title = column;
lv = j;
break;
}
}
if(title.length) {
let current_node = treechart_new_node(title);
// trim not used sub folder.
if(path_stock.length) {
path_stock = path_stock.slice(0,lv);
}
// force to push current node to stock.
path_stock.push(current_node);
if(lv==0) {
if(json_obj.length==0) {
json_obj.push(current_node);
}
} else {
if(json_obj.length==1) {
let last_node = path_stock[(lv-1)];
last_node.children.push(current_node);
}
}
}
}
}
轉換 json 為 csv:
主程式:
let json_obj = JSON.parse(jstree_node_json);
if(json_obj.length==1) {
jstree_node_json = json_obj[0].text + "\n";
const travel_result = treechart_travel_json_node(json_obj[0].children, ",")
jstree_node_json += travel_result;
}
副程式:
function treechart_travel_json_node(children, prefix) {
let ret = "";
if(children.length) {
for(let i=0; i<children.length; i++) {
const node = children[i];
ret = ret + prefix + node.text + "\n";
if(node.children.length) {
ret = ret + treechart_travel_json_node(node.children, prefix + ",");
}
}
}
return ret;
}