0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Node.js】複数のファイルパスをオブジェクトでの階層表現に変換する

Posted at

経緯

Node.jsのfsを使って特定のディレクトリの中身をファイルパスにて取得した際に、ディレクトリの階層と互換性のあるオブジェクトに変換したかった。

結論

index.js
const data = [
  '/public/aaa/1.file',
  '/public/aaa/2.file',
  '/public/bbb/1.file',
  '/public/ccc/1.file',
  '/public/ccc/2.file',
  '/public/ccc/3.file',
  '/public/ddd/1.file'
];

const output = {};
let current;

for (const path of data) {
    current = output;
    for (const segment of path.split('/')) {
        if (segment !== '') {
            if (!(segment in current)) {
                current[segment] = {};
            }
            current = current[segment];
        }
    }
}

console.log(output);

/* 実行結果
{ public:
   { 
     aaa: { '1.file': {}, '2.file': {} },
     bbb: { '1.file': {} },
     ccc: { '1.file': {}, '2.file': {}, '3.file': {} },
     ddd: { '1.file': {} } 
   } 
}
*/

あとは取得した結果から

子要素に値が入っていたらディレクトリ
子要素に値が入っていなかったらファイル

と認識して分岐させれば色々使えると思う。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?