Ron D.
Ron D.

Reputation: 3814

d3.js: Expand multiple paths in tree layout

My JSON contains same node names in different paths, I would like to be able to open all children with the same name or has substring in their names.

Tried this example: [Search Collapsible Tree], but it opens only one path.
The idea is to implement search for substring and a if a path has a node that contains the search term, then, open (expand) that path.

So, I replaced the Select2 to text input but the search is still limited to one result. enter image description here

Upvotes: 2

Views: 2745

Answers (1)

Nixie
Nixie

Reputation: 637

You just need to change tree search function to find all the nodes (and then, highlight everything):

	function searchTree(obj,search,path, paths){
		if(obj.name.indexOf(search) != -1){ //if search is found return, add the object to the path and return it
			path.push(obj);
			paths.push(path.slice(0)); // clone array
		}
		else if(obj.children || obj._children){ //if children are collapsed d3 object will have them instantiated as _children
			var children = (obj.children) ? obj.children : obj._children;
			for(var i=0;i<children.length;i++){
				path.push(obj);// we assume this path is the right one			  
				searchTree(children[i],search,path, paths);
				path.pop();
			}
		}
	}

...

	$("#search").on("select2-selecting", function(e) {
		var paths = [];
		searchTree(root,e.object.text,[], paths);
		if(paths.length > 0)
		{
			paths.forEach(function(p) { openPaths(p) });
			//openPaths(paths);
		}
		else{
			alert(e.object.text+" not found!");
		}
	})

Upvotes: 2

Related Questions