这是我的写法:
function arrToTree (arr, index = '', parentName) {
let tree = []
console.log(parentName);
let temp
for (let i = 0; i < arr.length; i++) {
console.log(temp);
let obj = {}
if (parentName && parentName == temp) {
let index = obj.id
let newArr = arr[i].slice(1)
obj.child.push(arrToTree(newArr, index, arr[i][0]))
} else {
if (!Array.isArray(arr[i])) {
obj = {
"id": `${index}0${i + 1}`,
"name": arr[i],
}
} else {
obj = {
"id": `${index}0${i + 1}`,
"name": arr[i][0],
}
}
temp = obj.name
if (Array.isArray(arr[i]) && arr[i].length > 1) {
let index = obj.id
let newArr = []
newArr = arr[i].slice(1)
obj.child = (arrToTree(newArr, index, arr[i][0]))
}
}
tree.push(obj)
}
return tree
}
let arr = [["hello", "bill"], ["hello", 'jack'], ["world", "foo", "jerry"], ["world", "foo", "peter", "tom"], ["world", "bar"]]
console.log(JSON.stringify(arrToTree(arr)));
写到这一步不知道,改怎么写了,主要是parentName和temp那一块有问题,求大佬指教