I am currently working on building a JSON object that updates dynamically as a node tree is constructed. The node tree will take user input and add it to the tree, while also updating the JSON object with the values. Here's what the JSON object should resemble:
jsonData={children:[{value: 'abc', id: '123', children:[{value:'cde', id:345, children[]}
]}
]}
In my implementation, the jsonData object does get updated, but I am facing challenges in pushing the child objects to the respective parent object children property.
All elements are considered children of the jsondata, yet achieving hierarchical updates has proven difficult.
My code:
<style>
.collapse > * {
display: none;
}
.expand > * {
display:block;
}
</style>
<script>
var jsonData = {children:[]};
document.addEventListener('DOMContentLoaded', function () {
var div = document.createElement('div');
div.innerHTML = "[+]" + "Root";
div.name = "root";
createProps(div);
function recurseTree(temp, parent, depth, parentObj) {
console.log(parentObj);
var children = parent.children;
++depth;
for (var i = 0, len = children.length; i < len; i++) {
var child = children[i];
var element = document.createElement('input');
element.addEventListener('keypress', function(e){
if(e.keyCode === 13){
var newElem = document.createElement('div');
newElem.innerHTML = element.value;
newElem.name = element.value;
newElem.innerHTML = '    '.repeat(depth) + '[+]' + element.value;
newElem.className = 'collapse';
var newObj = createProps(newElem);
console.log(parent);
parentObj.children.push(newObj);
temp.appendChild(newElem);
recurseTree(newElem, child, depth,parentObj);
}
})
temp.appendChild(element);
}
}
recurseTree(div, document.body, 0, jsonData);
document.body.appendChild(div);
console.log(jsonData)
div.addEventListener('click', function(event) {
if(event.target.className === "collapse"){
event.target.className = "expand";
}
else{
event.target.className = "collapse";
}
});
});
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x3|0x8)).toString(16);
});
return uuid;
};
function createProps(elem){
var obj = {}
obj.id = generateUUID();
obj.value = elem.name;
obj.children = [];
console.log(obj);
return obj;
}
</script>