¿Cómo construir un objeto de lista de menú recursivamente en JavaScript?
Con una matriz de
['/social/swipes/women', '/social/swipes/men', '/upgrade/premium'];
Me gustaría construir un objeto de mapa que se vea así:
{
'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 menu
// .slice returns a copy of the original array
.slice()
// convert the string to an array by splitting the /'s
// remove the first one as it's empty
// .map returns a new array
.map(item => item.split('/').splice(1))
// iterate through 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)
// set root to [root][label]
//root = ?
root = root[label];
}
});
}
buildMenuMap(menu);
console.log(map);
Pero no estoy seguro de cómo cambiar el valor deroot
.
¿Qué configuroroot
to para que recursivamente llame aaddLabelToMap
co
'[social]'
, 'swipes' => '[social][swipes]'
, 'women' => '[social][swipes]'
, 'men'
?
He usadoroot = root[element]
pero está dando un error.
as soluciones alternativas serían geniales, pero me gustaría entender por qué esto no funciona fundamentalmente.