2017-01-30 5 views
1

Я пытаюсь выяснить, как настроить путь с помощью lodash _.setWith. В данном примере здесь:Lodash _.setWith настроить путь

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

Выводит структуру, как это:

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

Можно ли получить что-то вроде этого, с настройщиком:

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

ответ

0

Вы хотите иметь ['a', 'children', 'b', 'children', 'c'].

Вы можете превратить ваш обр к чему-то вроде этого:

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

Другой простой способ сделать это, чтобы преобразовать каждый элемент в строку стенографии: [ «A», «B»] -> ' a.children.b ', который я делаю в следующем примере, объединив массив с .join ('. children. ').

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

https://jsfiddle.net/z2j1t10q/

+0

Великий и короткое решение, благодаря – janthoma

0

Вы можете добавить 'children' к пути с помощью _.zip() с массивом 'children', уплощение результат, и принимая все, кроме последнего пункта.

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>