简体   繁体   中英

How to access filtered data from pivottable.js

I would like to get the filtered data from my pivot table and use it for other purposes. As indicated in https://github.com/nicolaskruchten/pivottable/issues/626 the .onRefresh option accepts a function that has the pivot table configurations as argument.

The pivot table, however, apparently does not store a copy of either the filtered or unfiltered data. I have already tried to apply the filter method below, without success as it always return 'true':

onRefresh: function(config) {
    
    let filterInclusions = Object.keys(config.inclusions).length > 0;
    let filterExclusions = Object.keys(config.exclusions).length > 0;
            
    config.dataClass.forEachRecord(
        dataObject,
        config.derivedAttributes,
        record => {
            config.filter(record);
        })
    
}

The solution was to replicate the logic in https://github.com/nicolaskruchten/pivottable/blame/60389139da818ff3dc2f0243c7be72bf0b54a73b/src/pivot.coffee#L804 in a pure javascript function and apply it inside the .onRefresh callback.

An example (available at https://jsfiddle.net/90q26d87/ ) is presented below:

$("#output").pivotUI(
  dataObject, {
    rows: ["a", "b"],
    cols: ["c", "d"],
    vals: ["quantity", "value"],
    aggregatorName: "Sum over Sum",
    rendererName: "Heatmap",
    onRefresh: function(config) {
        
        let filterInclusions = Object.keys(config.inclusions).length > 0;
        let filterExclusions = Object.keys(config.exclusions).length > 0;
                
        config.dataClass.forEachRecord(
            dataObject,
            config.derivedAttributes,
            record => {
            // true : record has passed the filter
          filterRecord(config.inclusions, filterInclusions, config.exclusions, filterExclusions, record);
          // do something with record
            })
        
    }
    
  });
  
filterRecord = function(inclusions, filterInclusions, exclusions, filterExclusions, record) {
        for (const [recordKey, recordValue] of Object.entries(record)) {
            if (filterInclusions) {
                if (inclusions[recordKey] !== undefined) {
                    if (!inclusions[recordKey].includes(recordValue)) {
                        return false;
                    }
                }
            }
            if (filterExclusions) {
                if (exclusions[recordKey] !== undefined) {
                    if (exclusions[recordKey].includes(recordValue)) {
                        return false;
                    }
                }
            }
        }
        return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM