代码之家  ›  专栏  ›  技术社区  ›  totalnoob

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

  •  0
  • totalnoob  · 技术社区  · 6 年前

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

    building a menu list object recursively in javascript

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

    { 
        social: {
            swipes: {
                women: null
            }
        }
    }
    

    {
        social: {
            children: {
                swipes: {
                    children: {
                        women: null
                    }
                }
             }
         }
    }
    

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

    let input = ['/social/swipes/women', '/social/swipes/men', '/upgrade/premium'];
    
    let output = input.reduce((o, e) => {
      let z = e.split("/").filter(d => d);
      
      z.reduce((k,v,i) => {
    
        if (z.length - 1 !== i) {
          if (k.hasOwnProperty(v)) {
            k[v] = k[v];
          } else {
            k[v] = { children: {}};
          }
        } else {
          k[v] = null;
        }
    
        return k[v]
      }, o)
    
      return o;
    }, {})
    
    console.log(output);
    2 回复  |  直到 6 年前
        1
  •  4
  •   Nitish Narang    6 年前

    您可以像下面这样修改代码来实现这一点

    let input = ['/social/swipes/women', '/social/swipes/men', '/upgrade/premium'];
    
    let output = input.reduce((o, d) => {
      let keys = d.split('/').filter(d => d)
      
      keys.reduce((t, k, i) => {
        t[k] = (i != keys.length - 1)
                  ? (t[k] || { children: {} })
                  : null
    
        return t[k] && t[k].children
      }, o)
      
      return o
    }, {})
    
    console.log(output)
        2
  •  1
  •   Karan    6 年前

    let input = ['/social/swipes/women', '/social/swipes/men', '/upgrade/premium'];
    let output = {};
    
    input.forEach((x) => {
      var currentPath = output;
      var lastIndex = x.split('/').slice(1).length - 1;
      x.split('/').slice(1).forEach((y, index) => {
        currentPath.childern = currentPath.childern || {};
        currentPath.childern[y] = currentPath.childern[y] || {};
            
        if (lastIndex == index) {
          currentPath.childern[y] = null;
        }
        
        currentPath = currentPath.childern[y];
      });
    });
    
    output = output.childern;
    console.log(output);