JSFiddle - React, Tailwind, and code Playground
by murray_3
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].iid == id) {
return root.children[k];
}
else if (root.children.length) {
return findObjectById(root.children[k], 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);
}
}
}
//that's all... no magic, no bloated framework
var s =""
traverse(ob,s)
var bla = findObjectById(ob,11)
bla.children.push({
name: "child x",
id: 11111,
children: []
});
document.write(bla)
var s =""
traverse(ob,s)