2016-08-20 71 views
0

我想创建具有字符串数组的嵌套数组。 数组上的每个字符串对象都由'|'分隔并且该char用于在已经存在的数组上创建一个嵌套数组。如何基于javascript中的字符串数组创建嵌套数组?

编辑修复 IE:当前数组

var arr = [ 
    { val : 'root|leaf|lead2|boo|foo|lee'}, 
    { val : 'root|leaf|lead3|boo|foo|lee'}, 
    { val : 'root|leaf2|boo'}, 
    { val : 'root|leaf2|foo'}, 
    { val : 'root|leaf2|leaf3|more'}, 
    { val : 'root|leaf2|leaf3|things'}, 
    { val : 'root|leaf2|leaf3|here'}, 
    { val : 'sibling|leaf|leaf2|boo'}, 
    { val : 'sibling|leaf|leaf2|foo'}, 
    { val : 'sibling|leaf|leaf2|lee'}, 
    { val : 'sibling|boo'}, 
    { val : 'sibling|foo'}, 
    { val : 'sibling|boo|leaf3'}, 
    { val : 'sibling|boo|leaf3|more'}, 
    { val : 'sibling|boo|leaf3|things'}, 
    { val : 'sibling|boo|leaf3|here'}, 
    { val : 'sibling|ops'}, 
]; 

var nested = [ 
    root = [ 
     leaf = [ 
      leaf2 = [ 
       'boo', 'foo', 'lee' 
      ], 
      leaf3 = [ 
       'boo', 'foo', 'lee' 
      ] 
     ], 
     leaf2 = [ 
      'boo', 'foo', leaf3 = [ 
       'more', 'things', 'here' 
      ] 
     ] 
    ], 
    sibling = [ 
     leaf = [ 
      leaf = [ 
       leaf2 = [ 
        'boo', 'foo', 'lee' 
       ] 
      ] 
     ], 
     'ops', 
     'boo', 'foo', leaf3 = [ 
      'more', 'things', 'here' 
     ] 
    ] 
]; 
+0

你看看lodash LIB它不正是你需要 – hpfs

+0

我不是在JS是专家,你可以用一个例子尝试一下呢? – 9879800

+0

您的示例结果数组不包含有效的JavaScript。你能解决这个问题,所以我们知道如何帮助你,否则我们只会帮助你创建一个JavaScript错误而没有任何意义 – Delosdos

回答

1

你可以在这里找到一个功能的方法,通过使用.map().reduce()方法。这个想法是通过分解|字符来解析路径,然后即时构建对象。

const arr = [ 
    {cat : 'one|two|thre|boo'}, 
    {cat : 'one|two|boo|boo|ouch'}, 
    {cat : 'one|two|thre|boo|lee'}, 
    {cat : 'one|hey|something|other'}, 
    {cat : 'one|hey|keys|other'}, 
    {cat : 'this|blaj|something|other'}, 
]; 


function create(array) { 
    const parse = elm => elm.cat.split('|'); 

    const build = (keys, obj, acc) => { 
    keys.reduce((a, b) => { 
     if (!a[b]) a[b] = {}; 
     return a[b]; 
     }, obj); 
    Object.assign(acc, obj); 
    return acc; 
    }; 

    const obj = {}; 

    return array 
    .map(a => parse(a)) 
    .reduce((acc, keys) => build(keys, obj, {}), {}); 
} 

console.log(create(arr)) 

您可以找到Working plunkr

+0

你可以使它与ECMAScript 5.1兼容吗? – 9879800

+2

您只需用普通函数替换箭头函数,并用“var”替换关键字“const” –