How to get rendered tree data on page load

How can I get all rendered tree metadata on page load in jstree, something like this output:

[23,24]

Note: i want put each id in metadata object to be like this on page load [23,24]

$(function() {
  $('#jstree').jstree({
    "json_data": {
      "data": [{
        "data": "A node",
        "metadata": { id: 23 },
        "children": ["Child 1", "A Child 2"]
      }, {
        "metadata": { "id": 24 },
        "data": "Node 2",
      }]
    },
    "plugins": ["themes", "json_data", "ui"]
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://old.static.jstree.com/v.1.0pre/jquery.jstree.js"></script>
<div id="jstree">
</div>

1 answer

  • answered 2018-10-09 16:32 Rory McCrossan

    To retrieve the id values you can use map() on the array you provide to the jsTree instance, like this:

    $(function() {
      var treeStructure = [{
        "data": "A node",
        "metadata": { id: 23 },
        "children": ["Child 1", "A Child 2"]
      }, {
        "metadata": { "id": 24 },
        "data": "Node 2",
      }];
      
      var ids = treeStructure.map(function(o) {
        return o.metadata.id;
      });
      console.log(ids);
    
      $('#jstree').jstree({
        "json_data": {
          "data": treeStructure
        },
        "plugins": ["themes", "json_data", "ui"]
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="http://old.static.jstree.com/v.1.0pre/jquery.jstree.js"></script>
    <div id="jstree"></div>