var data = [
{
cid: "59eb15be",
parentCid: "",
lv: 1,
number: "2",
subject: "Title 2"
},
{
cid: "d7d851ef",
parentCid: "",
lv: 1,
number: "4",
subject: "Title4"
},
{
cid: "bd01cc50",
parentCid: "ae35e67d",
lv: 2,
number: "1.1",
subject: "Title1.1"
},
{
cid: "2d8bd8b0",
parentCid: "",
lv: 1,
number: "3",
subject: "Title3"
},
{
cid: "7f66a92d",
parentCid: "ae35e67d",
lv: 2,
number: "1.2",
subject: "Title1.2"
},
{
cid: "ae35e67d",
parentCid: "",
lv: 1,
number: "1",
subject: "Title1"
},
{
cid: "e7c2dbcc",
parentCid: "ae35e67d",
lv: 2,
number: "1.3",
subject: "Title1.3"
},
{
cid: "cc784c42",
parentCid: "ae35e67d",
lv: 2,
number: "1.4",
subject: "Title1.4"
}
];
var chapterListDiv = document.getElementById("listSummary");
var store = document.createDocumentFragment(); //we use this to store temporary orphaned childs
for(var i=0; i<data.length; i++){
var node = document.createElement("div");
node.className = "lv" + (data[i].level || data[i].lv);
var content = document.createTextNode(data[i].number + "." + " " + data[i].subject);
node.appendChild(content);
node.setAttribute("data-id", data[i].cid); //set a data-id attribute. We need it for the orphaned values.
node.setAttribute("data-parent-id", data[i].parentCid); //set a data-parent-id attribute. We need it for the orphaned values.
if (data[i].parentCid == "") //we have a root node
{
chapterListDiv.appendChild(node);
}
else
{
var parent = chapterListDiv.querySelector('div[data-id="'+data[i].parentCid+'"]'); //look for a node with the parent id.
if (parent) //parent is found
{
parent.appendChild(node);
}
else
{
store.appendChild(node); //temp store the node.
}
}
}
//final check
var storeChilds = store.querySelectorAll('div[data-parent-id]');
if (storeChilds)
{
Array.prototype.map.call(storeChilds, function(element){
var parent = document.querySelector('div[data-id="'+element.getAttribute("data-parent-id")+'"]') ||
store.querySelector('div[data-id="'+element.getAttribute("data-parent-id")+'"]')
parent.appendChild(element);
});
}
.lv1 {
}
.lv2{
padding-left: 30px;
}
.lv3{
padding-left: 30px;
}
<div id="listSummary"></div>
In json data, all item has a "cid" and some of them has "parentCid" which mean it is the child level of it.)
As second level of result
1.3. Title1.3
1.4. Title1.4
1.1. Title1.1
1.2. Title1.2
This is not order because "1.1" and "1.2" cannot find their parent node when access in loop because their parent node is behind them. So that is why "1.3" and "1.4" being append first(parent node is ahead).
Is there any way that can have result correctly like below for second level?
1.1. Title1.1
1.2. Title1.2
1.3. Title1.3
1.4. Title1.4