Como criar um objeto de lista de menus recursivamente em JavaScrip
Com uma matriz de
['/social/swipes/women', '/social/swipes/men', '/upgrade/premium'];
Gostaria de construir um objeto de mapa parecido com:
{
'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);
Mas não tenho certeza de como mudar o valor deroot
.
O que eu definoroot
para que recursivamente chameaddLabelToMap
com
'[social]'
, 'swipes' => '[social][swipes]'
, 'women' => '[social][swipes]'
, 'men'
?
Eu useiroot = root[element]
mas está dando um erro.
s soluções alternativas seriam ótimas, mas eu gostaria de entender por que isso não está funcionando fundamentalment