Reputation: 13
I started working with Javascript and Jquery couple of weeks ago. Now at the office I have to build a Object that contain Child and grandChild and etc..
I know the best way would be to perform a recursive function but can't figure it out. I have been able to work but as soon as i Have 2 level I fail...
I have this data :
dataTest = [
{ que_code: "BM1", que_enonce: "Test 1", que_id: "1", que_id_parent: null },
{ que_code: "BM2", que_enonce: "Test 2", que_id: "2", que_id_parent: 1 },
{ que_code: "BM3", que_enonce: "Test 3", que_id: "3", que_id_parent: 1 },
{ que_code: "BM4", que_enonce: "Test 4", que_id: "4", que_id_parent: null },
{ que_code: "BM5", que_enonce: "Test 5", que_id: "5", que_id_parent: 3 },
];
I result should give the following
Any help would be appreciated.
Thanks in advance
Upvotes: 0
Views: 843
Reputation: 122037
Here is how you can do this, you can first use recursion to create that tree data structure with reduce()
method and then you can create another recursive function that will build HTML from that new data structure.
var dataTest = [
{ que_code: "BM1", que_enonce: "Test 1", que_id: "1", que_id_parent: null },
{ que_code: "BM2", que_enonce: "Test 2", que_id: "2", que_id_parent: 1 },
{ que_code: "BM3", que_enonce: "Test 3", que_id: "3", que_id_parent: 1 },
{ que_code: "BM4", que_enonce: "Test 4", que_id: "4", que_id_parent: null },
{ que_code: "BM5", que_enonce: "Test 5", que_id: "5", que_id_parent: 3 },
];
function makeTree(data, parent = null) {
return data.reduce(function(r, e) {
if (e.que_id_parent == parent) {
e.child = makeTree(data, e.que_id)
r.push(e)
}
return r;
}, [])
}
function toHtml(data, parent) {
data.forEach(function(e) {
var li = $('<li></li>')
li.text(e.que_code)
if (e.child.length) {
var ul = $('<ul></ul>');
ul.append(toHtml(e.child, ul));
}
li.append(ul)
parent.append(li)
})
}
var newData = makeTree(dataTest, null);
toHtml(newData, $('ul'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- DON'T FORGET THIS UL -->
<ul></ul>
Upvotes: 2