I am currently creating a dynamic multidimensional array in Javascript. First of all I want to create a dynamic checklist array.
First I create my first checklist then I want to make a sub checklist for my main checklist. Then I want to create a sub checklist for that particular sub checklist also and so on.
see my below script
function get_item_checklist(){ //should convert the sample image to object
var arr = [];
$("#checklist-body").find("div.card").each(function(){
var list_name = $(this).find("list_name").val();
var $body = $(this).find("div.card-body div.list_item");
if($body.length){
var list_arr = [];
var list_rec = [];
$(body).each(function(){
var desc = $(this).find("input.desc").val();
var list_no = parseInt($(this).find("input.req-no").val()) - 1;
var sub_no = $(this).find("input.sub-no").val();
list_rec.push({"list_no":list_no,"sub_no":sub_no});
if(list_no && !sub_no){
if(!list_arr[list_no]){
list_arr[list_no] = [];
}
list_arr[list_no].push({"desc":desc}); // will simply just push since there is no sub#
}else if(list_no && sub_no){
sub_no = parseInt(sub_no) - 1;
var parent_nos = look_parent_list_no(list_rec,sub_no);
if(parent_nos){
if(parent_nos.length == 1){ //for only one parent checklist
if(!list_arr[parent_nos[0]][sub.no]){ //if not set
list_arr[parent_nos[0]][sub.no] = [];
}
list_arr[parent_nos[0]][sub_no].push({"desc":desc});
}else{
// if parent nos are multiple
// END OF MY SCRIPT HERE <<<<<<--------
}
}
}
});
arr.push({"name":list_name,"description":list_arr});
}else{
arr.push({"name":list_name});
}
});
};
function look_parent_list_no(arr,no,arr1){ // this will get all the list # of parents in order to know where to put exactly the sub checklist
if(typeof arr1 != "object"){
arr1 = [];
}
for(key in arr){
console.log(arr[key],no);
if(arr[key].list_no == no && !arr[key].sub_no){
arr1.push(arr[key].list_no);
return arr1;
}else if(arr[key].list_no == no && arr[key].sub_no){
arr1.push(arr[key].list_no);
return look_parent_list_no(arr,arr[key].sub_no,arr1);
}
}
return false;
};
I am now having a problem if a sub checklist have a parent of parent, you can see it in the list # 5. List 5 should be inside of list #4 where in list #4 is inside of list #2.
below object is my expected output to my get_item_checklist()
[
{
name: "My Parent list 1",
description :
[
{
desc: "sublist 1"
},
{
desc: "sublist 2",
items:
[
{
desc: "sublist 1 of 2"
},
{
desc: "sublist 2 of 2",
items: [
{
desc: "sublist 1 of 2 of 2"
}
]
}
]
}
]
}
]

Composite Design Pattern, you may want to look at this: (dofactory.com/javascript/composite-design-pattern)