Filter arrays using SQL like querystring
$ npm install @rusintez/qp --save
var filter = require('@rusintez/qp');
var assert = require('assert');
var arr = [{
bool_field: true,
another_bool_field: false,
a: 1,
b: 2,
c: 'blah',
d: [1, "2", true, false]
}];
var query = 'bool_field AND NOT another_bool_field AND a = 1 AND (b >= 2 OR c = "blah") AND d INCLUDES [1, "2", true]';
var result = filter(query, arr);
assert.deepEqual(arr, result);
var result = filter(query, list);
By default adapter is set to 'native' that uses tree-like structure to filter objects in an array. It's possible to use (included) sift.js filtering mechanism
var siftFilteredList = filter(query, list, 'sift');
a AND b
— true when both are true
a OR b
- true when either one is true
NOT c
— true if c is falsy
a EQUALS 5
— true when a is number 5
a = 5
— shorthand, same as above
a > 4
— true when a is greater than 4
a >= 4
— true when a is greater than or equals 4
a < 4
— true when a is less than 4
a <= 4
— true when a is less than or equals 4
tags INCLUDES ["russia", "china"]
— true when tags include both russia and china
tags IN ["us", "uk"]
— shorthand, same as above
Flags are shorthand expressions by them selves, eg.
has_active_license AND no_principal
will become has_active_license = true AND no_principal = true
Brackets are supported to ensure correct order or comparison
a = 5 OR (b = 10 AND c > 0) AND NOT tags IN ["blacklisted"]
"hello world"
— strings must be surrounded by double quotes
5
- for now only non-negative integers are supported, more coming soon
true
, false
null
[1,"2", false, [true, true], null]
— all of the above + nesting
It's possible to get back parsed query tree using excellent PEG generated parser.
var parser = require('@rusintez/qp/parser');
var assert = require('assert');
var tree = parser.parse('license_types INCLUDES 7');
assert.deepEqual(tree, {
token: 'INCLUDES',
key: 'license_types',
value: {
token: 'NUMBER',
value: 7
}
});
Vladimir Popov
MIT