Lodash _.setWith自定义路径

时间:2017-01-30 19:41:24

标签: javascript arrays object lodash

我试图弄清楚如何使用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: {}
              }
            }
          }
        }
      }
    }
  }
}

2 个答案:

答案 0 :(得分:1)

你想要的是[&#39; a&#39;,&#39;孩子&#39;&#39; b&#39;,&#39;孩子&#39;,&#39; C&#39;]

您可以将您的arr转换为以下内容:

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

另一种更简单的方法是将每个元素转换为字符串速记:[&#39; a&#39; a&#39; b&#39;] - &gt; &#39; a.children.b&#39;,我在下面的例子中通过将数组与.join(&#39; .children。&#39;)连接起来。

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

https://jsfiddle.net/z2j1t10q/

答案 1 :(得分:1)

您可以使用'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>