Create a object i an object based on the array of string value
Once you've split by slashes, use reduce
to iterate to the nested object, creating each nested property first if necessary, then assign an array to the filename property:
const myArray = [
'/unit/unit/225/unit-225.pdf',
'/nit/nit-dep/4.11/nit-4.11.pdf',
'/nit/nit-dep/4.12/nit-4.12.pdf',
'/org/viti/viti-engine/5.1/viti-engine-5.1.pdf',
'/org/viti/viti-spring/5.1/viti-spring-5.1.pdf'
];
var parentObject = {}
myArray.forEach((str) => {
const props = str.slice(1).split('/');
const filename = props.pop();
const lastObj = props.reduce((a, prop) => {
if (!a[prop]) {
a[prop] = {};
}
return a[prop];
}, parentObject);
lastObj[filename] = [];
});
console.log(parentObject);
You could reduce the array an reduce the path as well. At the end assign the array.
const
array = ['/unit/unit/225/unit-225.pdf', '/nit/nit-dep/4.11/nit-4.11.pdf', '/nit/nit-dep/4.12/nit-4.12.pdf', '/org/viti/viti-engine/5.1/viti-engine-5.1.pdf', '/org/viti/viti-spring/5.1/viti-spring-5.1.pdf'],
result = array.reduce((r, path) => {
var keys = path.split(/\//).slice(1),
last = keys.pop();
keys.reduce((o, k) => o[k] = o[k] || {}, r)[last] = [];
return r;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
A slightly faster approach.
const
array = ['/unit/unit/225/unit-225.pdf', '/nit/nit-dep/4.11/nit-4.11.pdf', '/nit/nit-dep/4.12/nit-4.12.pdf', '/org/viti/viti-engine/5.1/viti-engine-5.1.pdf', '/org/viti/viti-spring/5.1/viti-spring-5.1.pdf'],
result = {};
for (let path of array) {
let keys = path.split(/\//).slice(1),
last = keys.pop(),
temp = result;
for (let key of keys) {
temp[key] = temp[key] || {};
temp = temp[key];
}
temp[last] = [];
}
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }