.append () to select based on condition?

I have the same problem as in Updating SVG ZG Index from D3

My preferred solution would be to have two groups inside my svg, as described in notan3xit's answer .

But I have one dataset, and a boolean flag in one of the data properties determines which group the svg element belongs to.

svg.selectAll("path")
   .data(d)
   .enter()
   .if(d.property).appendToGroup1() 
   .else.appendToGroup2()

      

This obviously doesn't work, but something like this.

I only want to iterate over the data once and at runtime add the generated svg elements to the appropriate groups.

Any ideas on how to achieve this with d3.js?

+3


source to share


2 answers


Try

.each(function(d){
  var toAppend = $(this);
  if (!!d.property){
    toAppend.appendtoGroup1();
  } else {
    toAppend.appendToGroup2();
  }
  })//...

      



The general idea would be to pass d

to a callback and apply the right append method inside that callback. It needs to be cleaner to first keep a link to what you want to add in the enclosing scope so you can call .append()

on it easily .

+1


source


Try the following:

var selectedPath=svg.selectAll("path").data(d);
svg.selectAll("path").each(function(d,i){
      if(d3.select(this).attr("property name"))
         selectedPath.append("some data to group 1")
      else
         selectedPath.append("some data to group 2") 
 });

      



If I could improve the code.

0


source







All Articles