function tree(list) {
const result = [];
for (let value of list) {
// 排除空字符串的情況
if (!value) {
continue;
}
const values = value.split('/');
// 查找樹結構的當前級別是否已經存在,不存在則創建對象,並添加入列表。
let current = result.find(item => item.name === values[0]);
if (current === void 0) {
current = {};
result.push(current);
}
for (let i = 0, length = values.length; i < length; i++) {
current.name = values[i];
if (i < length - 1) {
// 如果還有下壹級內容,判斷當前是否有 children,沒有則構建.
if (current.children === void 0) {
current.children = [];
}
// 查找下壹級對象,為下壹遍遍歷構建對象
let nextCurrent = current.children.find(item => item.name === values[i + 1]);
if (nextCurrent === void 0) {
nextCurrent = {};
current.children.push(nextCurrent);
}
current = nextCurrent;
}
}
}
return result;
}
============ 假裝分割線 ===========
以上代碼是生成樹的函數,調用 tree 函數並傳入妳的 input 數據,返回值就是生成的樹。百科沒找到傳代碼的地方了。