Skip to content

Instantly share code, notes, and snippets.

@perXautomatik
Last active June 5, 2023 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perXautomatik/192be0a691dfad79a3d99f6fb98625b2 to your computer and use it in GitHub Desktop.
Save perXautomatik/192be0a691dfad79a3d99f6fb98625b2 to your computer and use it in GitHub Desktop.
javascript - Converting Tree Like File Directory to a JSON object - Stack Overflow
const input = [
'C:/Users/Freddy/System/storage/Objects/Users/1',
'C:/Users/Freddy/System/storage/Objects/Users/1/email',
'C:/Users/Freddy/System/storage/Objects/Users/1/email/FreddyMcGee@Gmail.com',
'C:/Users/Freddy/System/storage/Objects/Users/1/etc',
'C:/Users/Freddy/System/storage/Objects/Users/1/etc/etc',
'C:/Users/Freddy/System/storage/Objects/Users/1/password',
'C:/Users/Freddy/System/storage/Objects/Users/1/password/123123123213',
'C:/Users/Freddy/System/storage/Objects/Users/1/username',
'C:/Users/Freddy/System/storage/Objects/Users/1/username/Freddy1337'
];
const lastPart = str => str.match(/\/([^\/]+)$/)[1];
const [baseDirectory, ...keysVals] = input;
const dirName = lastPart(baseDirectory);
const dirObj = {};
for (let i = 0; i < keysVals.length; i += 2) {
const key = lastPart(keysVals[i]);
const val = lastPart(keysVals[i + 1]);
dirObj[key] = val;
}
const output = { [dirName]: dirObj };
console.log(output);
#Url https://stackoverflow.com/questions/51228768/converting-tree-like-file-directory-to-a-json-object'
cd 'B:\ToGit\DirToJson'
node javascript-converting-tree-like-file-directory-to-a-json-object-stack-overflow.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment