这是我的写法:
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那一块有问题,求大佬指教
###function c (arr) {
var ids = [],
result = [],
randomKey = Math.random().toString(32).slice(-8),
map = new Map();
function createItem (name, index) {
ids.length = index + 1;
ids[index] = (ids[index] || 0) + 1;
let cl = ids.slice(0, index + 1).map(k => String(k).padStart(2, '0')).join('');
return {
name,
id: cl
};
}
function add(list) {
let base,
vk = [];
list.forEach((o, i) => {
vk.push(o);
let d = vk.join(randomKey),
mo;
if (!map.has(d)) {
mo = createItem(o, i);
map.set(d, mo);
if (base) {
base.child = (base.child || []).concat(mo);
} else {
result.push(mo);
}
} else {
mo = map.get(d);
}
base = mo;
});
}
arr.forEach(k => add(k));
return result;
}
var t = [['hello','bil'],['hello','jack'],['world','foo','jerry'],['world','foo','peter','tom'],['world','bar']];
var result = c(t);
JSON.stringify(result, null, 4);