I\'m creating a table with d3 to be used by the FooTable jquery plugin and this requires having some data- attributes in the header row. But not all columns have all the data a
The most voted solution is perfect because .attr(a,b)
works as conditional when b
is null,
d3chain.attr('data-class', d=>'data-class' in d ? d['data-class'] : null );
but this solution is not geral, is not valid for other chaining methods, except using .each()
, .filter
or .call()
. In general the most simple is call()
.
Suppose that param
is an global variable used as parameter in the condition, and that g
is a global object used to return a value.
// inconditional
d3chain.attr(param, g[param])
// conditional case using globals
d3chain.call( s => { if (g[param]) s.attr(param,g[param]) })
// conditional case passing the parameter
d3chain.call( (s,p) => {
if (g[p]) s.attr(p, g[p])
}, param)
Typical use:
d3chain.each( d=> {
if (param && d) d3.select(this).attr(d, g[param])
})
See @nrabinowitz answer for detailed example.
Typical use:
d3chain.filter( d=> param in d ).attr(param, d=> g[param])
See @LarsKotthoff answer for detailed example.