Created
May 8, 2020 09:06
-
-
Save okumurakengo/b12bdf16cac76c1d6f07d182e198aa03 to your computer and use it in GitHub Desktop.
フォルダ階層たどってJSONにしてくれるの
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = ` | |
foo.html | |
bar/hoge/fuga.php | |
bar/hoge/piyo.php | |
bar/hogera.php | |
baz/fugara.php | |
` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const files = require("./files") | |
const res = files | |
.split("\n") | |
.filter(v => v !== "") | |
.map(path => path.split("/")) | |
.reduce((acc, filepath) => { | |
const last = filepath.pop() | |
const fn = (acc, arr, last) => { | |
if (arr.length === 0) { | |
acc.push(last) | |
return | |
} | |
const key = arr.shift() | |
const find = acc.find(obj => | |
typeof obj === "object" | |
&& key in obj) | |
const crrent = { [key]: [] } | |
if (!find) { | |
acc.push(crrent) | |
} | |
fn(find ? find[key] : crrent[key], arr, last) | |
} | |
fn(acc, filepath, last) | |
return acc | |
}, []) | |
console.log(JSON.stringify(res, null, ' ')) | |
// [ | |
// "foo.html", | |
// { | |
// "bar": [ | |
// { | |
// "hoge": [ | |
// "fuga.php", | |
// "piyo.php" | |
// ] | |
// }, | |
// "hogera.php" | |
// ] | |
// }, | |
// { | |
// "baz": [ | |
// "fugara.php" | |
// ] | |
// } | |
// ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment