In-Memory Array Querying with mongodb syntax queries (via Sift)

JS
S
JavaScript

Validate objects & filter arrays easily with Sift. Works for NodeJS and Browser (2KB size). Official Documentation https://github.com/crcn/sift.js Supported operators: $in, $nin, $exists, $gte, $gt, $lte, $lt, $eq, $ne, $mod, $all, $and, $or, $nor, $not, $size, $type, $regex, $where, $elemMatch

1const sift = require('sift');
2const array1 = ['hello', 'world'];
3const array2 = ['hello', 'sifted', 'array!'];
4
5// Intersect Test
6const queryIntersectArrays = sift({ $in: array1 }, array2);
7
8// Regex (first letter k)
9const queryRegex = sift(/^j/, ['abcd', 'jxxj', 'j', 'test']); //['john','jake']
10const queryRegex1 = sift(
11    { $regex: "^e", $options: "i", $nin: ["aa"] },
12    ["aa", "bb", "cc", "dd","ee"]
13); // ["ee"]
14
15
16// Function Queries
17const queryFn = sift({
18    laptop: function (value) {
19        return value.length > 4;
20    }
21});
22const res1 = queryFn({ laptop: 'macbook' }); //true
23const res2 = queryFn({ laptop: 'dell' }); //false
24
25// Array Filter
26const arr = [
27    {
28        laptop: 'macbook',
29    },
30    {
31        laptop: 'dell'
32    },
33    {
34        laptop: 'asus'
35    }
36].filter(queryFn);
37
38
39// OR Query Emulation
40const findOrQuery = sift(
41    {
42        brand: {
43            $in: ['Dell', 'Apple', 'Lenovo', 'HP']
44        }
45    },
46    [{ brand: 'Apple', model: 'Macbook' }, { brand: 'Dell', model: 'XPS' }]
47);
48
49// Not In
50const notInQuery = sift(
51    {
52        $nin: ['Dell', 'Apple', 'Lenovo', 'HP']
53    },
54    ['Dell', 'Apple', 'Lenovo', 'HP', 'Toshiba']
55);
56
57// Exists Query
58const laptops = [
59    { model: 'Macbook', brand: 'Apple' }, 
60    { model: 'XPS', brand: 'Dell' },
61    { brand: 'HP' }
62];
63const existsQuery = sift(
64    {
65        model: { $exists: false }
66    },
67    laptops
68);
69
70// Greater Than or Equal ($gt, $gte, $lt, $lte, $eq, $neq)
71const GTEQuery = sift(
72    { $gte: 2 },
73    [0, 1, 2, 3]
74);
75
76// Equal (strings)
77const EQQuery = sift(
78    { brand: {$eq: 'Apple' }},
79    laptops
80);
81
82// Mod (field/divisor has the remainder)
83const modQuery = sift(
84    { $mod: [3, 0] },
85    [100, 200, 150, 400, 500, 600]
86);

Created on 11/8/2017