使用子键在javascript中递归构建菜单列表对象

使用子键在javascript中递归构建菜单列表对象,javascript,Javascript,我一直在巩固以前的一篇文章 我用它来了解更多关于js和it输出中的数组和对象的信息 { social: { swipes: { women: null } } } 但现在我想要一种更实用的方式,使它更容易以如下格式遍历 { social: { children: { swipes: { children: {

我一直在巩固以前的一篇文章

我用它来了解更多关于js和it输出中的数组和对象的信息

{ 
    social: {
        swipes: {
            women: null
        }
    }
}
但现在我想要一种更实用的方式,使它更容易以如下格式遍历

{
    social: {
        children: {
            swipes: {
                children: {
                    women: null
                }
            }
         }
     }
}
用儿童钥匙

我如何修改代码才能做到这一点

let input=['/social/swipes/women','/social/swipes/men','/upgrade/premium'];
让输出=输入。减少((o,e)=>{
设z=e.split(“/”).filter(d=>d);
z、 减少((k,v,i)=>{
如果(z.长度-1!==i){
如果(k.hasOwnProperty(v)){
k[v]=k[v];
}否则{
k[v]={子代:{};
}
}否则{
k[v]=null;
}
返回k[v]
},o)
返回o;
}, {})

控制台日志(输出)您可以通过如下方式修改代码来实现此目的

let input=['/social/swipes/women','/social/swipes/men','/upgrade/premium'];
让输出=输入。减少((o,d)=>{
让keys=d.split(“/”).filter(d=>d)
减少((t,k,i)=>{
t[k]=(i!=keys.length-1)
?(t[k]|{子:{})
:null
返回t[k]&&t[k]。子级
},o)
返回o
}, {})

console.log(输出)
您可以像下面这样修改代码来实现这一点

let input=['/social/swipes/women','/social/swipes/men','/upgrade/premium'];
让输出=输入。减少((o,d)=>{
让keys=d.split(“/”).filter(d=>d)
减少((t,k,i)=>{
t[k]=(i!=keys.length-1)
?(t[k]|{子:{})
:null
返回t[k]&&t[k]。子级
},o)
返回o
}, {})
console.log(输出)
let input=['/social/swipes/women','/social/swipes/men','/upgrade/premium'];
让输出={};
input.forEach((x)=>{
var currentPath=输出;
var lastIndex=x.split('/')。切片(1)。长度-1;
x、 分割('/')。切片(1)。forEach((y,索引)=>{
currentPath.childern=currentPath.childern | |{};
currentPath.childern[y]=currentPath.childern[y]|{};
if(lastIndex==索引){
currentPath.childern[y]=null;
}
currentPath=currentPath.childern[y];
});
});
output=output.childern;
控制台日志(输出)
let input=['/social/swipes/women','/social/swipes/men','/upgrade/premium'];
让输出={};
input.forEach((x)=>{
var currentPath=输出;
var lastIndex=x.split('/')。切片(1)。长度-1;
x、 分割('/')。切片(1)。forEach((y,索引)=>{
currentPath.childern=currentPath.childern | |{};
currentPath.childern[y]=currentPath.childern[y]|{};
if(lastIndex==索引){
currentPath.childern[y]=null;
}
currentPath=currentPath.childern[y];
});
});
output=output.childern;
控制台日志(输出)