0
votes

I need help using a custom column filter for handling JS objects.

I have a slickgrid table where the values in one column are JS object:

[
  { id: "1234", text: "Batman"},
  { id: "2345", text: "Robin"}
]

I use a custom formatter to smash the object into a string:

// convert [{id:string, text:string}...] to string
const optionFormatter: Formatter = (row, cell, value, columnDef, dataContext: any) =>
  value ? value.map(o => o.text).join(', ') : '';

Which displays in slickgrid as

Batman, Robin

my slickgrid options use gridmenu and enables column filtering:

 this.gridOptions = {
  enableGridMenu: true,
  enableFiltering: true,
  enableAutoResize: true,
  enableColumnReorder: true
};

My columnDef enables filtering for this column:

{ 
  id: 'owners', 
  name: 'Owners', 
  field: 'owners', 
  sortable: false, 
  formatter: optionFormatter, 
  filterable: true
}

Everything works if the value in the cell is a string, but the filter doesn't work if the cell is an object. I assume the filter is searching the pre-formatted value.

Is there a way to provide the column with a custom filter function that knows how to search the JS object for the query string? For example if I could just search the JSON.stringify(value), that would be good enough.

Alternatively, this answer describes how I could use the formatter to store the formatted text as a different string property in dataContext. If I do that, how do I specify which property to filter, seeing as it is a different property than the column field?

1

1 Answers

0
votes

I found a workaround.

preprocess my data, calling JSON.stringify on all values that are objects:

flattenFeature(f: Feature): any{
  var res = {};
  for (var prop in f) {
    res[prop] = (typeof f[prop] === 'object') ? JSON.stringify(f[prop]) : f[prop];
  }
  return res;
}

Then in my formatter, I parse the json, before formatting:

// convert [{id:string, text:string}...] to string
const optionFormatter: Formatter = (row, cell, value, columnDef, dataContext) =>
  value ? JSON.parse(value).map(o => o.text).join(', ') : '';

This allows the standard string filter to search the stringify'd JSON