Reputation: 8506
data: [
{
cid: "211211",
parentCid: "212121",
level: 3,
number: "2.1.1",
subject: "Title 2.1.1"
},
{
cid: "111111",
parentCid: "",
lv: 1,
number: "1",
subject: "Title1"
},
{
cid: "222222",
parentCid: "",
lv: 1,
number: "2",
subject: "Title2"
},
{
cid: "212121",
parentCid: "222222",
lv: 2,
number: "2.1",
subject: "Title2.1"
},
{
cid: "333333",
parentCid: "",
lv: 1,
number: "3",
subject: "Title3"
}
]
Above is a sample of my json data and I want to append these data on webpage like below? (All item has a "cid" and some of them has "parentCid" which is the child level of it.)
1Title1
2Title2
2.1Title2.1
2.1.1Title2.1.1
2.2Title2.2
3Title3
4Title4 //If necessary
4.1Title4.1
4.2Title4.2
Below is my code and can can show lv1 item but have no idea what to do next.
var chapterListDiv = document.getElementById("listSummary");
for(var i=0; i<data.length; i++){
if(data[i].lv == 1){
var divLv1 = document.createElement("div");
divLv1.className = 'lv1';
var content = document.createTextNode(data[i].number + "." + " " + data[i].subject);
divLv1.appendChild(content);
chapterListDiv.appendChild(divLv1);
}
}
Upvotes: 0
Views: 94
Reputation: 13304
Results here: http://jsfiddle.net/ct9j3h4y/3/
Since your data object isn't ordered, you'll get orphaned nodes. I use a temporary storage facility for that.
The data is linear, but unordered. So two loops should do it:
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 loop, to put all orphans into place.
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);
});
}
The code is pretty straightforward until we come to the final part. There all the stored childs are selected based upon the parent id and added from the store into the tree.
Techniques used:
Upvotes: 1