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

标签 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: []
        }]
      }
    }
   ],
   .......
};

最佳答案

这应该让你开始:

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

关于javascript - 拆分数组中的字符串以创建菜单和子菜单数据结构的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48189330/

相关文章:

javascript - AngularJS错误: Cannot read property 'get' of undefined

php - 谁能指导我通过示例在 php 中使用 json 并在 android 中获取输出?

javascript - 如何使用 forEach 循环添加 Json 项?

javascript - 只需稍加调整即可创建从一个对象到另一个对象的 JSON 对象

javascript - 为什么json号变了,什么时候json.parse一个字符串?

javascript - 如何将额外的行添加到表中,既不在末尾也不在开头? - jQuery

javascript - 在 javascript 中创建对象作为函数 - 并在游戏中使用箭头键控制它们

javascript - 如何在每个类中找到 href 属性?

arrays - 如何使用字典调用函数?

c - 当我尝试使用二分搜索递归地计算数组中某个数字的出现次数时,为什么此代码会返回段错误?