const links = [
{
url: "public/map/SavageLove/SavageLove_AudioPreview.ogg/1.ogg",
timestamp: 123,
},
{
url: "public/map/SavageLove/SavageLove_AudioPreview.ogg/2.ogg",
timestamp: 127,
},
{
url: "public/map/Malibu/Malibu_AudioPreview.ogg/1.ogg",
timestamp: 123,
},
];
const obj = {};
links.forEach((link) => {
const elements = link.split("/");
for (const e in elements) {
}
});
const obj = {
"public/": {
"map/": {
SavageLove: {
"SavageLove_AudioPreview.ogg": [
{
url: "public/map/SavageLove/SavageLove_AudioPreview.ogg/1.ogg",
timestamp: 123,
},
{
url: "public/map/SavageLove/SavageLove_AudioPreview.ogg/2.ogg",
timestamp: 127,
},
],
},
Malibu: {
"Malibu_AudioPreview.ogg": [{
url: "public/map/Malibu/Malibu_AudioPreview.ogg/1.ogg",
timestamp: 123,
}],
},
},
},
};
links.reduce((acc, n) => {
const path = n.url.split('/');
const [ lastFolder ] = path.splice(-2);
(path.reduce((p, c) => p[c] ??= {}, acc)[lastFolder] ??= []).push(n);
return acc;
}, {})
links.reduce((acc, n) => (
n.url
.match(/[^\/]+(?=\/)/g)
.reduce((p, c, i, a) => p[c] ??= (-~i < a.length ? {} : []), acc)
.push(n),
acc
), {})
function setArrayAtPath(obj, path) {
return path.reduce((acc, val, i) => {
acc[val] ??= (i === path.length - 1) ? [] : {};
return acc[val];
}, obj);
}
const result = links.reduce((acc, val) => {
const fullPath = val.url.split('/');
const path = fullPath.slice(0, -1);
const dir = setArrayAtPath(acc, path);
let insertIdx = dir.findIndex(o => o.timestamp > val.timestamp);
insertIdx = insertIdx === -1 ? dir.length : Math.max(0, insertIdx - 1);
dir.splice(insertIdx, 0, { ...val });
return acc;
}, {});
console.log(result);