2017-01-30 4 views
1

Ich versuche herauszufinden, wie Sie den Pfad mit lodash _.setWith anpassen. In dem gegebenen Beispiel hier:Lodash _.setWith anpassen Pfad

var arr = 
[ 
    ['a'], 
    ['a','b'], 
    ['a','b','c'], 
    ['a','b','c','d'], 
] 

var object = {}; 

for (i = 0; i < arr.length; i++) { 
    _.setWith(object, arr[i], {'data' : {'path': 'path', 'title': 'title'}}, Object) 
} 

console.log(object) 

jsfiddle

Gibt eine Struktur wie folgt aus:

{ 
    a: { 
    data: {} 
    b: { 
     data: {} 
     c: { 
     data: {} 
     d: { 
      data: {} 
     } 
     } 
    } 
    } 
} 

Ist es möglich, so etwas zu bekommen, mit dem Customizer:

{ 
    a: { 
    data: {} 
    children: { 
     b: { 
     data: {} 
     children: { 
      c: { 
      data: {} 
      children: { 
       d: { 
       data: {} 
       children: {} 
       } 
      } 
      } 
     } 
     } 
    } 
    } 
} 

Antwort

0

Was Sie wollen, ist ['a', 'children', 'b', 'children', 'c'].

Sie können Ihre arr so etwas wie diese Transformation:

var arr = 
[ 
    ['a'], 
    ['a','children','b'], 
    ['a','children','b','children','c'], 
    ['a','children','b','children','c','children','d'], 
] 

Ein weiterer einfacher Weg, es zu tun, ist jedes Element auf den String Stenographie zu verwandeln: [ 'a', 'b'] -> ' a.children.b ', was ich im folgenden Beispiel mache, indem ich das Array mit .join ('. children. ') verknüpfe.

for (i = 0; i < arr.length; i++) { 
    _.setWith(
     object, 
     arr[i].join('.children.'), 
     {'data' : {'path': 'path', 'title': 'title'}}, 
     Object 
    ) 
} 

https://jsfiddle.net/z2j1t10q/

+0

Große und kurze Lösung, dank – janthoma

0

Sie können mit _.zip() mit einer Reihe von 'children', Abflachen des Ergebnisses, und nimmt alles, aber das letzte Element 'children' zu dem Pfad hinzufügen.

var arr = 
 
[ 
 
    ['a'], 
 
    ['a','b'], 
 
    ['a','b','c'], 
 
    ['a','b','c','d'], 
 
] 
 

 
var object = {}; 
 
var children = _.fill(new Array(arr.length), 'children'); // the children array size is like the longest path 
 

 
for (i = 0; i < arr.length; i++) { 
 
    var path = _(arr[i]) 
 
    .zip(children) // zip it with the children array 
 
    .flatten() // convert it to a single array 
 
    .take((i + 1) * 2 - 1) // take everything but the last 
 
    .value(); 
 

 
    _.setWith(object, path, { 
 
     data : {'path': 'path', 'title': 'title'}, 
 
     children: {} 
 
    }, Object) 
 
} 
 

 
console.log(object)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>