2016-09-04 64 views
-1

我有分層的JSON,並希望轉換爲平坦的JSON沒有父子。分層json與父ID平坦

vm.str = [ 
    { 
     "s_gid": 0, 
     "title": "scholastic Master List 2016", 
     "nodes": [ 
      { 
       "Id": "1", 
       "templateId": "1", 
       "s_gid": "10", 
       "m_s_p_id": "1", 
       "subject_group_name": "xxxxxxx", 
       "parent_id": "1", 
       "sname": "", 
       "nodes": [ 
        { 
         "Id": "2", 
         "templateId": "1", 
         "s_gid": "100", 
         "m_s_p_id": "0", 
         "subject_group_name": "abc", 
         "parent_id": "10", 
         "sname": "", 
         "nodes": [ 
          { 
           "Id": "3", 
           "templateId": "1", 
           "s_gid": "1000", 
           "m_s_p_id": "0", 
           "subject_group_name": "efg", 
           "parent_id": "100", 
           "sname": "" 
          } 
         ] 
        } 
       ] 
      } 
     ] 
    } 
] 

什麼轉換爲新vm.str2 = []平,在同級別無節點...子節點的所有節點..

回答

0

可以使用遞歸函數返回的對象

var arr =[{"s_gid":0,"title":"scholastic Master List 2016","nodes":[{"Id":"1","templateId":"1","s_gid":"10","m_s_p_id":"1","subject_group_name":"xxxxxxx","parent_id":"1","sname":"","nodes":[{"Id":"2","templateId":"1","s_gid":"100","m_s_p_id":"0","subject_group_name":"abc","parent_id":"10","sname":"","nodes":[{"Id":"3","templateId":"1","s_gid":"1000","m_s_p_id":"0","subject_group_name":"efg","parent_id":"100","sname":""}]}]}]}] 
 

 
function flatten(data) { 
 
    var result = []; 
 
    data.forEach(function(o) { 
 
    var obj = {} 
 
    for(var e in o) { 
 
     (Array.isArray(o[e])) ? result.push(...flatten(o[e])) : obj[e] = o[e]; 
 
    } 
 
    result.push(obj) 
 
    }) 
 
    return result; 
 
} 
 

 
console.log(flatten(arr))

+0

謝謝。它正在工作,但我得到4 braket「[[[[」從開始 – fresher

+0

確保你寫完全相同的代碼,再次檢查這部分'result.push(... flatten(o [e]))'也許你忘了' ......傳播運營商。 –

+0

@fresher代替'...'擴展運算符,你也可以像這樣使用'concat()'https://jsfiddle.net/Lg0wyt9u/1217/ –

0

你可以使用Array.prototype.reduce()加上遞歸此任務:

function getNodes(inputArr) { 
    return inputArr.reduce(function (prev, value) { 
     return prev.concat(
      [ value ], 
      (value.nodes ? getNodes(value.nodes) : []) 
     ); 
    }, []); 
} 

如果您仍然想刪除nodes,你既可以使用Array.prototype.map甚至Array.prototype.each

output = output.map(function (value) { 
    value.nodes = undefined; 

    return value; 
}); 
+0

不能夠使用它的一個陣列。投擲錯誤備忘錄未定義。你能打印到控制檯嗎? – fresher

+0

犯了一個錯誤,應該是「prev」而不是「memo」。 – mdziekon