将二维数组转换为 javascript 中的嵌套结构

Transform 2 dimensional array to nested structure in javascript

我想将二维数组转换为嵌套结构,如下所示 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":[]}]
        }]
   }
]

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

提前致谢。

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

# 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 , 将其作为可能的根删除 if parent).

优雅?可能是。至少对我来说看起来干净且易于理解。