2017-06-27 6 views
1

Par exemple, je voudrais analyser le tableau suivant:Parse tableau plat dans une structure imbriquée (arbre)

var array1 = ["a.b.c.d", "a.e.f.g", "a.h", "a.i.j", "a.b.k"] 

dans:

var json1 = { 
    "node": "a", 
    "leaf": false, 
    "children": [{ 
      "node": "b", 
      "leaf": false, 
      "children": [{ 
        "node": "c", 
        "children": [{ 
         "node": "d", 
         "leaf": true, 
         "children": [] 
        }] 
       }, 
       { 
        "node": "h", 
        "leaf": true, 
        "children": [] 
       } 
      ] 
     }, 
     { 
      "node": "e", 
      "leaf": false, 
      "children": [{ 
       "node": "f", 
       "leaf": true, 
       "children": [] 
      }] 
     }, 
     { 
      "node": "g", 
      "leaf": true, 
      "children": [] 
     } 
    ] 
} 

Je pense que d3.js fournit une bon moyen de le faire, mais je ne peux pas trouver un bon exemple.

Merci pour toute aide!

+0

Jetez un oeil à https://stackoverflow.com/questions/44679971/create-nested-object-from-multiple-string-paths/44680094#44680094 –

Répondre

2

Vous pouvez utiliser une approche de table de hachage imbriquée pour créer une arborescence.

var nodes = ["a.b.c.d", "a.e.f.g", "a.h", "a.i.j", "a.b.k"], 
 
    result = []; 
 

 
nodes.forEach(function (a) { 
 
    a.split('.').reduce(function (r, k, i, kk) { 
 
     if (!r[k]) { 
 
      r[k] = { _: [] }; 
 
      r._.push({ node: k, leaf: i + 1 === kk.length, children: r[k]._ }); 
 
     } 
 
     return r[k]; 
 
    }, this); 
 
}, { _: result }); 
 

 
console.log(result[0]);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

oh bien, merci beaucoup! – luthien