VagueExplanation VagueExplanation - 1 year ago 71
Javascript Question

Best way to create many branching arrays in JavaScript

I could write shorthand objects, but then I'll have a ton of indents of other arrays and objects inside. This is for a question form with many branching new sets of questions based on the last one anawered. Any suggestions on how this code should be designed?

Answer Source

Other solution with less typing:

var d = {
'':  {/*data*/},
'1': {/*data*/},
'1.1': {/*data*/},
'': {/*data*/}
for(var k in d){//build tree structure
  var a = k.split('.')
  var i = a.pop()
  var parent = a.join()
  if(parent in d){//parent exists
    d[parent].children.push({i: +i, k: k})//to prevent holes
  else {
    console.log('pending subtree: ' + k)
for(var k in d){//transform child array
  d[k].children = d[k].children
    .sort(function(a,b){return a.i-b.i})
    .map(function(x){return d[x.k]})