javascriptnode.jstreemodel

tree-model-js how to get previous node id


I wanted to know the previous visited node from tree. trying with below example

var TreeModel = require('tree-model');
tree = new TreeModel();

rootMain = tree.parse({
    id: 1,
    children: [
        {
            id: "11",
            children: [{id: "111"}]
        },
        {
            id: "12",
            children: [{id: "121"}, {id: "122"}]
        },
        {
            id: "13"
        }
    ]
});

If suppose I traverse to the node 121 and 122 I wanted the parent node then it should return me the 12 If suppose I traverse to the node 111 I wanted the parent node then it should return me the 11 If suppose I traverse to the node 13 I wanted the parent node then it should return me the 1


Solution

  • While traversing the tree you can get the parent of the current node with node.parent.

    rootMain.walk(node => {
      console.log('node id:', node.model.id);
    
      if(node.parent) {
        console.log('parent node id:', node.parent.model.id);
      }
    });