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.
Install the package via npm:
npm install als-json-filter
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 }
]
const filter = createFilter({ age: { $gt: 30 } });
console.log(filter({ age: 31 })); // true
console.log(filter({ age: 30 })); // false
const filter = createFilter({ age: { $lte: 20 } });
console.log(filter({ age: 20 })); // true
console.log(filter({ age: 21 })); // false
const filter = createFilter({ username: { $regex: '^[a-z0-9_-]{3,16}$' } });
console.log(filter({ username: 'user_123' })); // true
console.log(filter({ username: 'not_valid!' })); // false
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
const filter = createFilter({ email: { $exists: true } });
console.log(filter({ email: 'user@example.com' })); // true
console.log(filter({ username: 'user123' })); // false
const filter = createFilter({ count: { $type: 'number' } });
console.log(filter({ count: 10 })); // true
console.log(filter({ count: 'ten' })); // false
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
als-json-filter
is MIT licensed.