2016-08-20 38 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」 –

相關問題