student student - 3 months ago 14
JSON Question

How to put filteration expressions in vars in dc.js?

In our

powered
d3.js
chart.

Trying to concatenate a few boolean expressions inside crossfilter's's
filter
function by using code appending approach.



var field1 = true,
field2 = "XYZ",
field3 = "ABC",
field4 = 1
var filteredData = jsonObject.filter(function(d) {

//condition 1
if (field1 != true && field2 != "GHI") {
var _dataFilter = d.FieldOne >= field1 &&
d.FieldTwo <= field2 &&
d.FieldThree == field3 &&
d.FieldFour == field4
}

return _dataFilter;
});

console.log("FieldOne " + field1 + " FieldTwo " + field2 + " FieldThree " + field3 + " FieldFour " + field4);

var sourceDataForChart = crossfilter(filteredData);





I'm finding that
_dataFilter
is coming as nothing on console. By this, I mean literally nothing. No undefined, no object, no value, no function is returned.
sourceDataForChart
is the data being used by the chart

I need to implement it for a grouping requirement, there will be a lot of conditions.
How do I do it?

Answer

I agree with Ethan that this is JavaScript question.

Usually you don't want functions that will return undefined in some circumstances, and a value in other circumstances. Your variable _dataFilter will only get initialized if the conditions are true - and right now the condition is false because field1is true.

In fact, it's only because JavaScript hoists all variables to the function scope that the variable even exists when it's returned. So maybe this is why the debugger is reporting no value.

A better organization for the code would be

var filteredData = jsonObject.filter(function(d) {
  var _dataFilter = false;
  // condition 1
  if (field1 != true && field2 != "GHI") {
      _dataFilter = d.FieldOne >= field1 &&
        d.FieldTwo <= field2 &&
        d.FieldThree == field3 &&
        d.FieldFour == field4
  }
  else if (/* more conditions */ ) {
       _dataFilter = /* ... */
  }
  return _dataFilter;
});