tree-model-js get first siblings

282 Views Asked by At

Please find the tree

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"
        }]
    },
    {id: 2,
    children: [
        {
            id: "21",
            children: [{id: "211"}]
        },
        {
            id: "22",
            children: [{id: "221"}, {id: "222"}]
        },
        {
            id: "23"
        }
    ]});
  1. Suppose I'm on node 2 I wanted to know its first sibling so it should return me 1.
  2. Second I'm on node 13 / 12 I wanted to know its first sibling then it should return 11.
  3. Second I'm on node 122 I wanted to know its first sibling then it should return 121.

Guide me how can I achieve this. I tried with walk and find method but no luck.

1

There are 1 best solutions below

0
On

First get a reference to the node you are, assume 122:

var node122 = rootMain.first(n => n.model.id === "122")

Then get the reference to the parent and get the first child:

var firstSiblingOfNode122 = node122.parent.children[0]