I'm trying to create a nested array from within a function which currently looks like this:
function browse(url, arrayName) {
let data2 = [];
fs.readdir(url, (err, files) => {
if (err) throw err
files.forEach(file => {
try {
data.push({
'name': file,
'path': path.join(url, file)
})
}
catch(e) {
console.log(e)
}
})
data2.push({'images': data})
res.json(data2)
})
}
what i want to achieve is that i can pass a string to the function that can be used inside of the array, where it currently is hard coded data2.push({'images': data})
so that a function call like browse('path/to/folder', 'cool images')
will output
{ "cool images":
{
"name": "dog.png",
"path": "path/to/folder/dog.png"
},
{
"name": "cat.png",
"path": "path/to/folder/cat.png"
}
}
I've tried for a while but I can't seem to achieve this and I am also aware that the output currently isn't even proper JSON format – both of which likely stem from the fact that I don't really know the right JSON syntax. There surely must be a nicer way to achieve nested objects than pushing an array into another array…
I'd greatly appreciate a bump in the right direction!
thanks :~)