JSFiddle - React, Tailwind, and code Playground
HTML
<div sid="1" pid="0">
<div sid="2" pid="1">
<div sid="5" pid="2">
<div sid="6" pid="5"></div>
</div>
</div>
<div sid="7" pid="2">
<div sid="8" pid="7"></div>
</div>
<div sid="3" pid="1">
<div sid="4" pid="3"></div>
</div>
</div>
JavaScript
var _json = {};
function addTreeNode(div, parentObj) {
var childObj = {
sid: $(div).attr("sid"),
pid: $(div).attr("pid")
}
// add this to it's parent in the JSON hierarchy
if (!parentObj.children) parentObj.children = [];
parentObj.children.push(childObj);
// keep adding for all children div's
$(div).find("div").each(function() {
addTreeNode(this, childObj);
});
}
// start at the roots, it will magically work it's way out to the leaves
$("body > div").each(function(){
addTreeNode(this, _json);
});
console.log(_json);