1

In the tree object I'm working with, a node may have a 'children' property that can contain an array of child nodes. It's a concept for a multilevel menu structure.

What I'd like to achieve is to dynamically add a reference to the parent in the children.

I'm stuck at the point where I should mutate the original object. I cannot figure out how to do that properly.

The code snippet begins with an example object. It is followed by a recursive function that visits every node and holds reference to the parent, but does not modify the object. Then there is a function that modifies the object, but to only 3 levels in depth.

var obj = {
  id: "a",
  children: [{
      id: "b",
      children: [{
        id: "c"
      }]
    },
    {
      id: "d"
    }
  ]
};


function visitNode(node, parent) {
  if (node.children) {
    console.log('node with children', node, 'parent\'s ID is:', parent.id);
    node.children.forEach(child => visitNode(child, node));
  } else {
    console.log('node with no children:', node, 'parent\'s ID is:', parent.id);
  }
}
visitNode(obj, {id: null});

function mutate(obj) {
  obj.parentId = null;
  if (obj.children) {
    obj.children.forEach((child, i) => {
      obj.children[i].parentId = obj.id;
      if (child.children) {
        child.children.forEach((child2, j) => {
          obj.children[i].children[j].parentId = obj.children[i].id;
        })
      }
    })
  }
}

mutate(obj);
console.log('mutated object', obj);

2
  • do you like to add a back reference to the parent? Commented Aug 18, 2017 at 8:34
  • @NinaScholz: yes, that's what I'd like to do. Commented Aug 18, 2017 at 8:35

1 Answer 1

2

You could use a recursive function which is called with the actual object and the parent reference. If children exist, the children are iterated and the function is called again with the actual reference.

This proposal creates circular references to the object (that means, JSON.stringify may not work).

function setParent(object, parent) {
    object.parent = parent;
    object.children && object.children.forEach(function (o) {
        setParent(o, object);
    });
}

var object = { id: "a", children: [{ id: "b", children: [{ id: "c" }] }, { id: "d" }] };

setParent(object);

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.