Skip to content

Instantly share code, notes, and snippets.

@kawashimaken
Created March 12, 2019 03:56
Show Gist options
  • Save kawashimaken/3b5d664d8fcd365578ccacc91273b672 to your computer and use it in GitHub Desktop.
Save kawashimaken/3b5d664d8fcd365578ccacc91273b672 to your computer and use it in GitHub Desktop.
Convert file path string to json tree
var _ = require('lodash');
var paths = [
'/FolderC/FolderA/FolderQ/ItemA',
'/FolderC/FolderA/Item1',
'/FolderD/FolderF/FolderM/ItemA',
'/FolderD/FolderF/FolderM/ItemB',
'/FolderD/FolderG/ItemD',
'/ItemInRoot'
];
function pathString2Tree(paths, cb) {
var tree = [];
//ループする!
_.each(paths, function (path) {
// currentLevelを rootに初期化する
var pathParts = path.split('/');
pathParts.shift();
// currentLevelを rootに初期化する
var currentLevel = tree;
_.each(pathParts, function (part) {
// pathが既存しているかどうかをチェックする
var existingPath = _.find(currentLevel, {
name: part
});
if (existingPath) {
// Pathはすでにツリー構造に入っているので、追加しない
// current levelを下の子供階層に設定し直す
currentLevel = existingPath.children;
} else {
var newPart = {
name: part,
children: [],
}
currentLevel.push(newPart);
currentLevel = newPart.children;
}
});
});
cb(tree);
}
pathString2Tree(paths, function (tree) {
console.log('tree: ', JSON.stringify(tree));
});
@100milliongold
Copy link

素敵なコードです。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment