【问题标题】:building a menu list object recursively in javascript with a child key使用子键在javascript中递归构建菜单列表对象
【发布时间】:2018-11-26 18:10:20
【问题描述】:

我一直在建立之前的帖子

building a menu list object recursively in javascript

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

{ 
    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);

【问题讨论】:

    标签: javascript


    【解决方案1】:

    你可以修改下面的代码来实现这个

    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】:

      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);

      【讨论】:

        猜你喜欢
        • 2019-04-17
        • 2017-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-21
        • 1970-01-01
        相关资源
        最近更新 更多