I have several arrays as the following:
[ 'businessOpenAccount', 'accountSettings1.page.js' ]
[ 'businessOpenAccount', 'accountSettings2.page.js' ]
[ 'mainTest', 'test', 'test1.page.js' ]
[ 'mainTest', 'test', 'test2.page.js' ]
My expected result is to have an object in this way:
{
businessOpenAccount: {
'accountSettings1.page.js': {},
'accountSettings2.page.js': {}
},
mainTest: {
test: {
'test1.page.js': {},
'test2.page.js': {}
}
}
}
So actually I want to parse the arrays and build a nested object to return from them, but being sure to check that if a property already exists (because defined from a previous array) I won't override it, but just add the new nested property in it, respecting the correct order of nesting.
I tried few approaches using reduce, reduceRight and simple forEach/for loops but I still cannot really achieve the solution I would like.
Any tips please?
This is the best way I have so far, but I override the properties cycling over multiple arrays (the example with a single array):
const relevantFilePath = ['businessOpenAccount', 'accountSettings.page.js'];
let obj = {};
relevantFilePath.forEach((el, ind) => {
if (ind === 0) {
obj[el] = {};
previousEl = obj[el];
} else {
previousEl[el] = {};
previousEl = previousEl[el];
}
});
console.log(obj);