Skip to main content
Version: Next

Adding and removing query properties

Adding properties

To enhance a query object with additional properties, iterate through the rules array recursively. The transformQuery utility function simplifies this process.

The example below (inspired by issue #226) demonstrates adding the inputType property from the fields array to each rule in the query object.

import type { Field, RuleGroupType, RuleType } from 'react-querybuilder';
import { transformQuery } from 'react-querybuilder';

const fields: Field[] = [
{ name: 'description', label: 'Description', inputType: 'string' },
{ name: 'price', label: 'Price', inputType: 'number' },
];

const ruleProcessor: RuleProcessor = (r, { fieldData }): RuleType & { inputType?: string } => ({
...r,
inputType: fieldData?.inputType,
});

const result = transformQuery(query, { ruleProcessor });
Manual recursion

This example (taken directly from issue #226) shows how to use manual recursion to achieve the same result as the transformQuery example above.

import type { Field, RuleGroupType, RuleType } from 'react-querybuilder';

const fields: Field[] = [
{ name: 'description', label: 'Description', inputType: 'string' },
{ name: 'price', label: 'Price', inputType: 'number' },
];

const processRule = (r: RuleType): RuleType & { inputType?: string } => ({
...r,
inputType: fields.find(f => f.name === r.field)?.inputType,
});

const processGroup = (rg: RuleGroupType): RuleGroupType => ({
...rg,
rules: rg.rules.map(r => {
if ('field' in r) {
return processRule(r);
}
return processGroup(r);
}),
});

const result = processGroup(query);

Removing properties

To create a JSON string from a query object containing only specific properties, use the replacer parameter (second argument) of the JSON.stringify function.

const query: RuleGroupType = {
id: 'root',
combinator: 'and',
rules: [
{
field: 'firstName',
operator: '=',
value: 'Steve',
},
],
};

// This omits all properties except those specified in the replacer array:
console.log(JSON.stringify(query, ['rules', 'field', 'operator', 'value']));
// '{"rules":[{"field":"firstName","operator":"=","value":"Steve"}]}'

Alternatively, the formatQuery function provides a convenient method to generate a JSON string containing all query properties except id and path:

console.log(formatQuery(query, 'json_without_ids'));
// '{"combinator":"and","rules":[{"field":"firstName","operator":"=","value":"Steve"}]}'