als-json-filter
v1.0.0
Published
A versatile JSON filtering utility that mimics database query functionality for JSON objects.
Downloads
5
Maintainers
Readme
als-json-filter
als-json-filter
is a versatile utility for filtering JSON objects based on a variety of conditions, similar to querying databases but applicable in general JavaScript environments. This package allows users to apply complex query conditions to JSON data structures, making it ideal for data processing tasks in both frontend and backend applications.
Installation
Install the package via npm:
npm install als-json-filter
Usage
To use als-json-filter
, import the function and define your filter criteria:
const createFilter = require('als-json-filter');
const filter = createFilter({
age: { $gt: 18, $lt: 65 },
name: { $regex: '^[a-zA-Z]+$' }
});
const data = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 17 },
{ name: 'Charlie', age: 70 }
];
const filteredData = data.filter(filter);
console.log(filteredData);
This will output:
[
{ name: 'Alice', age: 25 }
]
Examples of Filter Operators
Greater Than ($gt)
const filter = createFilter({ age: { $gt: 30 } });
console.log(filter({ age: 31 })); // true
console.log(filter({ age: 30 })); // false
Less Than or Equal To ($lte)
const filter = createFilter({ age: { $lte: 20 } });
console.log(filter({ age: 20 })); // true
console.log(filter({ age: 21 })); // false
Regex Match ($regex)
const filter = createFilter({ username: { $regex: '^[a-z0-9_-]{3,16}$' } });
console.log(filter({ username: 'user_123' })); // true
console.log(filter({ username: 'not_valid!' })); // false
Logical OR ($or)
const filter = createFilter({
$or: [
{ age: { $lt: 20 } },
{ age: { $gt: 50 } }
]
});
console.log(filter({ age: 18 })); // true
console.log(filter({ age: 30 })); // false
console.log(filter({ age: 60 })); // true
Property Exists ($exists)
const filter = createFilter({ email: { $exists: true } });
console.log(filter({ email: '[email protected]' })); // true
console.log(filter({ username: 'user123' })); // false
Type Matching ($type)
const filter = createFilter({ count: { $type: 'number' } });
console.log(filter({ count: 10 })); // true
console.log(filter({ count: 'ten' })); // false
Supported Filter Operators
als-json-filter
supports a range of operators, similar to those found in MongoDB:
- $gt: Greater than
- $gte: Greater than or equal to
- $lt: Less than
- $lte: Less than or equal to
- $eq: Equal
- $ne: Not equal
- $in: Included in an array
- $nin: Not included in an array
- $regex: Matches regex
- $or: Logical OR
- $and: Logical AND
- $not: Logical NOT
- $nor: Logical NOR
- $exists: Property exists
- $type: Type of property matches
License
als-json-filter
is MIT licensed.