我有一个带有嵌套子项的数据数组,如下所示:
var Tabledata = [{
"id" : 2,
"children" : [{
"id" : 3,
"children" : [{
"id" : 5,
"children" : []
}, {
"id" : 7,
"children" : []
}]
}]
我希望将所有带有父ID或仅有子ID的子ID放入数组中。 像ids = [2,3,5,7]
或者我从mysql表中获得了完整的数据:
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
}]
如果我有一个父ID = 2,那么想要得到任何深度的所有嵌套子ID。像childs = [3,5,7]
答案 0 :(得分:0)
您可以尝试这样的事情:
function findId(data) {
var arr = [];
(function req(data) {
data.forEach(function(item) {
arr.push(item.id);
if (item.children) {
req(item.children);
}
})
})(data)
return arr;
}
<强> DEMO 强>
答案 1 :(得分:0)
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);
});
答案 2 :(得分:0)
Using underscore js module at server side node js , answer will be :
admin