fresher fresher - 2 months ago 18
Javascript Question

Hierarchical json to flat with parent ID

I have Hierarchical JSON and want to convert to flat JSON without parent child.

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": ""
}
]
}
]
}
]
}
]


what to convert to new vm.str2 = [] as flat, all nodes at same level without nodes ... sub nodes..

Answer

You can use recursive function to return one array of objects

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))

Comments