加入同一阵列下的文件夹文件

时间:2019-03-07 10:33:00

标签: node.js

我想将具有相同文件夹的文件放入同一阵列

这是我的代码:

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" }
  }
]

1 个答案:

答案 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);