var xlsx2json = require("node-xlsx");
var list = xlsx2json.parse("./test3.xlsx");
var fs = require("fs")
let testarr = [
['教育心理学', '教育心理学概述', '教育心理学的基本内涵', '研究对象与研究内容', '概念'],
[null, null, null, null, '学科性质'],
[null, null, null, null, '研究内容', '五要素三过程'],
[null, null, null, '教育心理学与普通心理学的关系'],
[null, null, null, '教育心理学的作用', '描述'],
[null, null, null, null, '解释'],
[null, null, null, null, '预测'],
[null, null, null, null, '控制'],
[null, null, "教育心理学的发展史", "初创时期", "裴斯泰洛齐"],
[null, null, null, null, "赫尔巴特"],
[null, null, null, null, "桑代克"],
[null, null, null, "发展时期", "小原又一"],
[null, null, null, null, "廖世承"],
[null, null, null, "成熟时期", "布鲁纳"],
]
createTree(list[0].data)//使用node读取的数组数据
// createTree(testarr)//测试,使用testarr数据可直接查看生成的数据,测试数据采用真实的一部分数据
// let totalobj={"id":"0_0","text":"教育心理学","children":[{"id":"0_1","text":"教育心理学概述","children":[{"id":"0_2","text":"教育心理学的基本内涵","children":[{"id":"0_3","text":"研究对象与研究内容","children":[{"id":"0_4","text":"概念"}]}]}]}]}
// let resultObj= getMergeTree(totalobj,{"id":"1_4","text":"学科性质"})
// console.log(JSON.stringify(resultObj));
function createTree(arr) { //生成最终树
let renderTree = {}
arr=JSON.parse(JSON.stringify(arr))
arr.forEach((element, index) => {
let result = arrToJson(element, index);
if (Object.keys(renderTree).length > 0) {
renderTree = getMergeTree(renderTree, result)
} else {
renderTree = getMergeTree(result, null)
}
});
writeJson(renderTree)
}
function arrToJson(arr, column) { //将数组转换为嵌套的json对象
let MaxLength = arr.length - 1;
let deep = {}
for (let index = MaxLength; index >= 0; index--) {
if (arr[index] === null) {
break;
}
let obj = {};
if (Object.keys(deep).length > 0) {
let childArr = []
obj['id'] = String(column) + '_' + String(index)
obj['text'] = arr[index]
childArr.push(deep)
obj['children'] = childArr;
deep = obj
} else {
obj['id'] = String(column) + '_' + String(index)
obj['text'] = arr[index]
deep = obj
}
}
return deep;
}
function getMergeTree(parentobj, currentobj) { //生成合并的树
if (currentobj == null) {
return parentobj;
}
let resultObj = {}
DFS(parentobj, currentobj);
function DFS(parentobj, currentobj) {
let idNumber;
try {
idNumber = Number(currentobj.id.split('_')[1]) - 1
} catch (error) {
idNumber = -10;
}
let child = parentobj.children;
if (child !== undefined && child.length > 0) {
let childrenLength = child.length - 1
let parentId = Number(parentobj.id.split('_')[1])
if (parentId == idNumber) {
child.push(currentobj)
}
DFS(child[childrenLength], currentobj)
resultObj = parentobj
}
}
return resultObj
}
function writeJson(arrlist) {
fs.writeFile('person.json', JSON.stringify(arrlist), function (err) {
if (err) {
console.error(err);
}
console.log('----------新增成功-------------');
})
}
博客地址:https://www.cnblogs.com/zzh965390267