【发布时间】:2019-04-17 22:23:33
【问题描述】:
有一个数组
['/social/swipes/women', '/social/swipes/men', '/upgrade/premium'];
我想构造一个如下所示的地图对象:
{
'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);
但我不确定如何切换root的值。
我将 root 设置为什么,以便它递归调用 addLabelToMap
'[social]', 'swipes' => '[social][swipes]', 'women' => '[social][swipes]', 'men'?
我使用了root = root[element],但它给出了一个错误。
替代解决方案会很棒,但我想了解为什么这从根本上不起作用。
【问题讨论】:
-
不应该
men在likes对象而不是swipes对象中? -
我刚刚编辑了它
标签: javascript arrays ecmascript-6 javascript-objects arrow-functions