我想将具有相同文件夹的文件放入同一阵列
这是我的代码:
const pathFile = [
'modules/main/main1/main.js',
'modules/server/server1/server.js',
'modules/server/server2/server.js',
];
pathFile.forEach((p) => {
const middle = p.split(/\//g);
middle.pop();
const fileFolder = middle[Math.floor(middle.length - 1) / 2];
array.push({ folder: fileFolder, files: { name: p } });
});
这是我得到的结果:
[
{ "folder": "main", "files": { "name": "modules/main/main1/main.js" } },
{
"folder": "server",
"files": { "name": "modules/server/server1/server.js" }
},
{
"folder": "server",
"files": { "name": "modules/server/server2/server.js" }
}
]
答案 0 :(得分:1)
您可以reduce
到由folder
索引的对象中,如果需要,可以创建关联的folder
对象,推送到files
数组,然后获取该对象的值:
const pathFile = [
'modules/main/main1/main.js',
'modules/server/server1/server.js',
'modules/server/server2/server.js',
];
const obj = pathFile.reduce((a, name) => {
const folder = name.split('/')[1];
if (!a[folder]) {
a[folder] = { folder, files: [] };
}
a[folder].files.push({ name });
return a;
}, {});
const arr = Object.values(obj);
console.log(arr);