Reputation: 469
I want to convert an array of file&folder paths into tree object(an array of object below, the children points to the array of itself):
type TreeItem<T> = {
title: T
key: T
type: 'tree' | 'blob'
children: Array<TreeItem<T>>
}
The file&folder paths come from the "git ls-tree -r -t HEAD" command which lists the tree object of a git repository, it looks as below:
100644 blob 68afe6febb3f4ab2155b436e2e5a43f62399388b LICENSE
100644 blob 78d926deaf73e93c12257d0be9dc10f39662aad0 README.md
040000 tree eefd18d086bb6089a4e392bda3105fd32399146b app
100644 blob 631e6d753849db0ed05d0124ab62c8e5522f1c32 app/.npmrc
100644 blob 72da957f1fec5b3dec8e89e9ab9364bb96a929b0 app/.yarnrc
100644 blob cb66e81274ca308805350d8c1ccc68811994ed1c app/app-info.ts
100644 blob 1bf399b381dab7c260c1dc4126025c7ab1a437af app/git-info.ts
100644 blob ec6e40fb46f6554d62823e5f27a8743de594acff app/package-info.ts
100644 blob bf92f9a597bfd8b8e9b2308a4848faa6937f4a1e app/package.json
040000 tree dd30a6b5ee422a42da4561ea8443ef8a4a82c078 app/src
040000 tree c8473c433cf8ec2a3d9b67171cff665d7176f264 app/src/ask-pass
100644 blob 76adbc48d6d239fd39eab1ea08c8ee2408df3ece app/src/ask-pass/ask-pass.ts
100644 blob e1de6d753ce44680071ab7c67615e2d81b279c21 app/src/ask-pass/main.ts
...
As you see, I can tell wheter it's a file or folder by the second column. And I defined a structure as below for the file&folder object above:
interface GitTreeObject {
readonly type: string
readonly hash: string
readonly path: string
}
Which means I want to convert the Array<'GitTreeObject> into Array<'TreeItem>. Anyone know how to implement the convert? It's better to implement by Typescript.Thanks in advance.
My requiment is similar with this one, and I tried to reference the answer of that question, but failed
Upvotes: 2
Views: 3046
Reputation: 386680
By taking only the pathes, you could split them an reduce the path until you get an object. In this object, you could later add the wanted data.
var data = ['LICENSE', 'README.md', 'app', 'app/.npmrc', 'app/.yarnrc', 'app/app-info.ts', 'app/git-info.ts', 'app/package-info.ts', 'app/package.json', 'app/src', 'app/src/ask-pass', 'app/src/ask-pass/ask-pass.ts', 'app/src/ask-pass/main.ts'],
result = {};
data.forEach(p => p.split('/').reduce((o, k) => o[k] = o[k] || {}, result));
console.log(result);
Upvotes: 15