数组一:(不限制长度)
[
["1", "1-1", "1-1-2"],
["1", "1-1", "1-1-3", "1-1-3-1"],
["2", "2-4", "2-4-1"],
["2", "2-5", "2-5-3"]
]
转换成
数组二:
[
{
code: "1",
children: [
{
code: "1-1",
children: [
{
code: "1-1-2",
children: []
},
{
code: "1-1-3",
children: [
{
code: "1-1-3-1",
children: []
}
]
}
]
}
]
},
{
code: "2",
children: [
{
code: "2-4",
children: [
{
code: "2-4-1",
children: []
}
]
},
{
code: "2-5",
children: [
{
code: "2-5-3",
children: []
}
]
}
]
}
]
实现方法:
function composeTree(list = [], parentIndex, parentValue) {
var arr = [];
var check = []
list.forEach(item => {
if (item.length >= parentIndex + 1) {
if (check.indexOf(item[parentIndex]) < 0 && (parentValue == 0 || item[parentIndex - 1] == parentValue)) {
var obj = {};
obj.code = item[parentIndex];
obj.children = composeTree(list, parentIndex + 1, item[parentIndex]);
arr.push(obj);
}
}
check.push(item[parentIndex]);
})
return arr;
}
感谢朋和晋提供帮助。