javascript - converting a flat nested data into single array -


i have data array nested child given below :

var tabledata  = [{ "id" : 2, "children" : [{     "id" : 3,     "children" : [{         "id" : 5,         "children" : []     }, {         "id" : 7,          "children" : []     }] }] 

i want child ids parent id or child ids array. ids = [2,3,5,7]

or have complete data mysql table given below :

data = [{ "id" : 7, "department_name" : "newupdate", "display_name" : "newupfate", "description" : "new", "parent_department_id" : 3, "is_child_company" : true, "status" : true, "created_on" : "2015-03-17t06:24:45.000z", "created_by" : 1 }, { "id" : 5, "department_name" : "first department child1s child1s child", "display_name" : "safdc1c1c", "description" : "", "parent_department_id" : 3, "is_child_company" : true, "status" : true, "created_on" : "2015-02-17t12:50:14.000z", "created_by" : 1  }, { "id" : 4, "department_name" : "second department", "display_name" : "sd", "description" : "", "parent_department_id" : null, "is_child_company" : false, "status" : true, "created_on" : "2015-02-17t12:50:14.000z", "created_by" : 1 }, { "id" : 3, "department_name" : "first department child1s child", "display_name" : "fdc1c1", "description" : "", "parent_department_id" : 2, "is_child_company" : true, "status" : true, "created_on" : "2015-02-17t12:50:14.000z", "created_by" : 1 }, { "id" : 2, "department_name" : "first department child1", "display_name" : "fdc1", "description" : "", "parent_department_id" : 1, "is_child_company" : true, "status" : true, "created_on" : "2015-02-17t12:50:14.000z", "created_by" : 1 }, { "id" : 1, "department_name" : "first department", "display_name" : "fd", "description" : "", "parent_department_id" : null, "is_child_company" : false, "status" : true, "created_on" : "2015-04-14t06:55:24.000z", "created_by" : 1  }]     

if have parent id =2 want nested child id of depth.like childs =[3,5,7]

    var data = [{         "id": 2,         "children": [{       "id": 3,      "children": [{        "id": 5,        "children": []      }, {        "id": 7,         "children": []      }]    }]     }];  var flatdata =[];  function flat(fdata){     $(fdata).each(function(){         flatdata.push($(this)[0].id);         if($(this)[0].children.length>0){             ($(this)[0].children)         }     });  }   $(document).ready(function(){      flat(data);      console.log(flatdata);  }); 

http://jsfiddle.net/lhxz1spl/


Comments