Having an assortment of
['/social/swipes/women', '/social/swipes/men', '/upgrade/premium'];
The objective is to create a map object that mirrors this structure:
{
'social': {
swipes: {
women: null,
men: null
}
},
'upgrade': {
premium: null
}
}
const menu = ['/social/swipes/women', '/social/likes/men', '/upgrade/premium'];
const map = {};
const addLabelToMap = (root, label) => {
if(!map[root]) map[root] = {};
if(!map[root][label]) map[root][label] = {};
}
const buildMenuMap = menu => {
menu
// make a copy of the menu
.slice()
// convert each string into an array by splitting at /
.map(item => item.split('/').splice(1))
// loop over each array and its elements
.forEach((element) => {
let root = map[element[0]] || "";
for (let i = 1; i < element.length; i++) {
const label = element[i];
addLabelToMap(root, label)
root = root[label];
}
});
}
buildMenuMap(menu);
console.log(map);
However, there seems to be confusion on how to update the value of root
.
What should I set root
to in order to correctly call addLabelToMap
with
'[social]'
,
'swipes' => '[social][swipes]'
, 'women' => '[social][swipes]'
, 'men'
?
I attempted using root = root[element]
but it resulted in an error.
If you have alternative solutions, feel free to suggest them. It's important for me to grasp why this approach is not functioning as intended.