在javascript中将2维数组转换为嵌套结构

时间:2018-03-07 03:46:12

标签: javascript coffeescript

我想将二维数组转换为嵌套结构,如下面javascript中所示。

输入:

[[A,B,C],[A,B,E],[A,M,N]]

输出:

[ {"name":A,"children":
        [{"name":B,"children":
            [{"name":C,"children":[]},{"name":E,"children":[]}]
        },
        {"name":M,"children":
            [{"name":N,"children":[]}]
        }]
   }
]

如果有任何优雅的解决方案可以解决这个问题,请告诉我。

提前致谢。

1 个答案:

答案 0 :(得分:0)

如果数组数组中的数组实际上是通过树的路径,并且您正在尝试构建这些路径描述的子树,那么您可以根据需要创建和缓存节点:

String pa = @"C:\Users\user\AppData\Local\Temp\2\db5fjamk.xnl";
System.IO.Directory.CreateDirectory(pa);
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; //f:\projectpath\out\debug-i386-unittest\UnitTests
setup.ApplicationName = string.Concat(AppDomain.CurrentDomain.FriendlyName, DateTime.UtcNow.Ticks); //UnitTestAdapter: Running test636559691791186101
setup.DynamicBase = pa;
Evidence evidence = AppDomain.CurrentDomain.Evidence;
_Domain = AppDomain.CreateDomain(setup.ApplicationName, evidence, setup);

然后在树中构建路径的简单方法:

# cache.by_id could be seen as a bit of a hack, don't
# forget to reset it in real life (or wrap this up in
# a class and use an instance variable for `by_id`).
cache = (id) ->
  if id of cache.by_id
    there = true
  else
    cache.by_id[id] = { name: id, children: [ ] }
    there = false
  [cache.by_id[id], there]
cache.by_id = { }

然后你可以遍历路径:

push = (parent, id) ->
  [child, there] = cache(id)
  parent?.children.push(child) if(!there)
  child

或:

paths = [
  ['A', 'B', 'C'],
  ['A', 'B', 'E'],
  ['A', 'M', 'N'],
  ['A', 'X', 'Y', 'Z'],
]

for path in paths
  parent = null
  for child in path
    parent = push(parent, child)

然后看for path in paths path.reduce(push, null) 。或者通过跟踪缓存中的父项(以便根将是没有父项的节点)来跟踪根,或直接跟踪cache.by_id.A中的根与另一个对象(将其添加为根push ,将其删除为可能的根if !there)。

优雅?也许。至少看起来干净易懂。