输入:const data = ['app/index.ts', 'app/folder1/File1.tsx', 'app/folder1/File2.tsx', 'app/data/Data1.ts', 'app/data/Data2.ts', 'app/style.ts']预期输出分组路径:const
输入:
const data = [
'app/index.ts',
'app/folder1/File1.tsx',
'app/folder1/File2.tsx',
'app/data/Data1.ts',
'app/data/Data2.ts',
'app/style.ts'
]
预期输出分组路径:
const output = {
"app": {
files: ['index.ts', 'style.ts'],
folder1: {
files: ["File1.tsx", "File2.tsx"],
},
data: {
files: ["Data.ts", "Data2.ts"],
}
}
}
我编写的函数输出错误:
const data = [
'app/index.ts',
'app/folder1/File1.tsx',
'app/folder1/File2.tsx',
'app/data/Data1.ts',
'app/data/Data2.ts',
'app/style.ts'
];
function convertData(data) {
const output = {};
data.forEach(path => {
const pathSegments = path.split('/');
const [root, ...rest] = pathSegments;
let currentLevel = output;
rest.forEach((segment, index) => {
if (!currentLevel[segment]) {
currentLevel[segment] = index === rest.length - 1 ? [] : {};
}
currentLevel = currentLevel[segment];
});
if (Array.isArray(currentLevel)) {
currentLevel.push(pathSegments[pathSegments.length - 1]);
} else {
currentLevel.files = currentLevel.files || [];
currentLevel.files.push(pathSegments[pathSegments.length - 1]);
}
});
return output;
}
const out = convertData(data);
console.log(out);