In my application I create a JavaScript object based on a JSON response from the server similar to this:
{
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: []
}
]
}
I create a new node such as:
{name: "grandchild three", id: 113, children:[]}
With this in mind, how can I add this new grandchild to its parent with id 11? Please note that I don’t know the static path to node with id == 11
so I am wondering how I could obtain that node with just knowing it's id
.
Edit: please note the id's in the real case do NOT encode the path to objects. I created this simple example for demonstration of the data structure I am dealing with. But I can not retrieve the path to the object using its id in my real application.
See this fiddle: http://jsfiddle.net/2Dvws/
It will find an object by ID. And push the new child. Since every object within Javascript is a reference, you can return it as an var.
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: []}
]
};
The function which will return the found element. Will look into all child elements.
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);
}
}
}
};
var bla = findObjectById(ob, 111);
console.log(bla);
bla.children.push({
name: "child x",
id: 1111,
children: []
});
console.log(ob);
Output is that child with id 111 will have 1 child with id 1111
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With