Created
March 12, 2019 03:56
-
-
Save kawashimaken/3b5d664d8fcd365578ccacc91273b672 to your computer and use it in GitHub Desktop.
Convert file path string to json tree
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
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)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
素敵なコードです。