arrays - How to dynamically add reference to parent in a javascript multilevel object? -


in tree object i'm working with, node may have 'children' property can contain array of child nodes. it's concept multilevel menu structure.

what i'd achieve dynamically add reference parent in children.

i'm stuck @ point should mutate original object. cannot figure out how properly.

the code snippet begins example object. followed recursive function visits every node , holds reference parent, not modify object. there function modifies object, 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 children', node, 'parent\'s id is:', parent.id);      node.children.foreach(child => visitnode(child, node));    } else {      console.log('node 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);

you use recursive function called actual object , parent reference. if children exist, children iterated , function called again actual reference.

this proposal creates circular references 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; }


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -