Anton Anton - 4 months ago 37
JSON Question

Filter JSON data depending on selected jsTree node

I have an example in fiddle. I have a tree like this:

> Root > Parent[n] > Child[n].


In
Child
I have added an event handler. In the example it is in
Child1
, so if I click on
Child1
it will render a table with 3 rows from the variable
array
.

What I want is if I click on
Child1
it will filter the table (
array
) by branch "Parent1", this is, it will render the table with 2 rows named "Parent1". Is there any way to do that?

Answer

I had to do two things to make your code work:

  1. add jsTree css to make it expandable
  2. you attached the select_node handler to something with id $study while it should have been jstree:

    $('#jstree').on('select_node.jstree', function (evt, data) {...})
    

Check update on this Fiddle.

You could simplify your code a little, if you care - Fiddle.

UPDATE

If you want to filter the array by the parent text of selected node, you can replace this line: $table.bootstrapTable('load', array);

with:

var parentNodeId = $('#jstree').jstree().get_node(data.selected[i]).parent;    
var parentNodeText = $('#jstree').jstree().get_node(parentNodeId).text;

var filteredArray = array.filter(function(item){
   if (item.name === parentNodeText) {
       return item;
   }  
});

$table.bootstrapTable('load', filteredArray);