【问题标题】:Algorithm to split strings in array to create a menu and submenus data structure在数组中拆分字符串以创建菜单和子菜单数据结构的算法
【发布时间】:2018-01-10 14:13:20
【问题描述】:

我有一个 Javascript 字符串数组,例如:

var array = [{
  string: 'path1/path2/path3'
}, {
  string: 'path1/path4/path5'
}, {
  string: 'path1/path2/path6'
}, {
  string: 'path10/path7'
}, {
  string: 'path10/path8/path9'
}];

我需要创建一个结构如下的数据模型:

-- path1
  -- path2
    -- path3
    -- path6
  -- path4
    -- path5
-- path10
  -- path7
  -- path8
    -- path9

我怎样才能做到这一点?你有什么建议吗?谢谢

编辑:

我在想这样的事情:

var paths = {
  children = [
    { 
     name: "path1"
     children: [
      { 
       name: "path2", 
       children: [
        { 
         name: "path3", 
         children: []
        }]
      },
      {
       name: "path4", 
       children: [
        { 
         name: "path5", 
         children: []
        }]
      }
    }
   ],
   .......
};

【问题讨论】:

  • 请添加所需结果的类型 - 它是数据结构(对象/数组/树)、HTML 结构还是其他?你试过什么,什么不起作用?
  • 我希望结果是一个对象,以便创建 HTML 菜单。我正在尝试找到一种智能方法来创建对象。

标签: javascript arrays json string algorithm


【解决方案1】:

这应该让你开始:

var array = [{
  string: 'path1/path2/path3'
}, {
  string: 'path1/path4/path5'
}, {
  string: 'path1/path2/path6'
}, {
  string: 'path10/path7'
}, {
  string: 'path10/path8/path9'
}];

let tree = {};

for (let {string} of array) {
    let t = tree;
    for (let c of string.split('/'))
        t = t[c] || (t[c] = {});
}

console.log(tree);

【讨论】:

  • 谢谢@georg 这是开始的东西,但在 HTML 中使用它不是很好。
  • 很好的解决方案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-24
  • 2017-06-20
  • 1970-01-01
相关资源
最近更新 更多