johnny
johnny

Reputation: 9036

How to find, insert and delete properties in a recursive, nested Object

I have a JavaScript object that looks as follows:

var obj = {

  "id": 1098
  "someData": {},
  "children": [
    {
      "id": 2124
      "someData": {},
      "children": [...]
    },
    {
      "id": 1298,
      "someData": {},
      "children": [
        {
          "id": 1290,
          "someData": {},
          "children": [...]
        }
      ]
  ]

}

As you can see the parent is always an object with an id, some data and children that have the same structure as the parent. In theory it can be nested infinitely.

I need two operations now: add and delete somewhere in this structure.

Maybe there is even a framework that works with recursive data?

Upvotes: 1

Views: 789

Answers (1)

Gilsha
Gilsha

Reputation: 14591

You will have to find the required object using a recursive method. Fetch and push the new data or delete object.

function findObjectById(root, id, action) {
    if (root.children) {
        for (var k in root.children) {
            if (root.children[k].id == id) {
                if(action=="fetch")
                  return root.children[k]; 
                else 
                   delete root.children[k];
            }
            else if (root.children[k].children.length) {
                return findObjectById(root.children[k], id);
            }
        }
    }
};

Push new data like this.

var parent = findObjectById(obj, 1298, "fetch");
parent.children.push({
        someData: {},
        id: 1234,
        children: []
});

Delete object like this.

findObjectById(obj, 2124, "delete");

Upvotes: 0

Related Questions