JSFiddle - React, Tailwind, and code Playground
JavaScript
var ob = {
name: "root",
id: 1,
children: [
{
name: "child one",
id: 11,
children: [
{
name: "grand child 1",
id: 111,
children: []},
{
name: "grand child 2",
id: 112,
children: []}
]},
{
name: "child two",
id: 12,
children: []}
]
};
function findObjectById(root, id) {
if (root.children) {
for (var k in root.children) {
if (root.children[k].id == id) {
return root.children[k];
}
else if (root.children.length) {
return findObjectById(root.children[k], id);
}
}
}
};
;
function findObjectByLabel(obj, id) {
for (i in obj.children) {
if(obj.children[i].id === id) {
document.write( obj.children[i].id);
return obj.children[i].children;
}
else {
findObjectByLabel( obj.children[i], id);
}
}
};
function traverse(o,spc) {
for (i in o) {
//func.apply(this,[i,o[i]]);
if(i == "name"|| i == "id") {
document.write(spc + i + " : "+o[i]+"<br>");
}
if (typeof(o[i])=="object") {
//going on step down in the object tree!!
ss = spc+"_"
traverse(o[i],ss);
}
}
}
function testpush(o,idd,tt,tid) {
for(var a = 0; a < o.children.length; a++) {
if(o.children[a].id == idd) {
o.children[a].children.push({
name: tt,
id: tid,
children: []
});
}
else {
testpush(o.children[a],idd,tt,tid);
}
}
};
testpush(ob,12,"test 121",121)
testpush(ob,121,"test 1211",1211)
console.log("fwfsd",ob);
//that's all... no magic, no bloated framework
var s =""
traverse(ob,s)
var boo = findObjectByLabel(ob,11)
//var boo = findObjectByLabel(ob,111)
boo.push({
...