在数组中拆分字符串以创建菜单和子菜单数据结构的算法

时间:2018-01-10 14:13:21

标签: javascript arrays json string algorithm

我有一个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: []
        }]
      }
    }
   ],
   .......
};

1 个答案:

答案 0 :(得分:2)

这应该让你开始:



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