I want to transform 2-dimensional array to the nested structure as shown below in javascript.
Input:
[[A,B,C],[A,B,E],[A,M,N]]
Output:
[ {"name":A,"children":
[{"name":B,"children":
[{"name":C,"children":[]},{"name":E,"children":[]}]
},
{"name":M,"children":
[{"name":N,"children":[]}]
}]
}
]
Please let me know if there is any elegant solution to solve this.
Thanks in advance.
If the arrays in your array-of-arrays are actually paths through a tree and you're trying to build the subtrees that those paths describe then you could create and cache nodes as needed:
# 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 = { }
and then an easy way to build the paths in the tree:
push = (parent, id) ->
[child, there] = cache(id)
parent?.children.push(child) if(!there)
child
Then you can loop through the paths:
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)
or:
for path in paths
path.reduce(push, null)
Then look at cache.by_id.A
. Or keep track of the roots as you go by tracking parents in the cache (so that the roots will be nodes without parents) or directly track roots in push
with another object (add it as a root if !there
, remove it as a possible root if parent
).
Elegant? Maybe. Looks clean and easy to understand to me at least.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.