Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@100milliongold 100milliongold commented Oct 8, 2020

素敵なコードです。

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