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

时间:2018-11-26 18:10:21

标签: javascript

我一直在上一篇文章的基础上

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

2 个答案:

答案 0 :(得分:2)

您可以修改以下代码以实现此目的

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)

答案 1 :(得分:1)

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