Build a predicate from an object of conditions
Build a predicate from an object of conditions in JavaScript, matching records whose fields equal the given values, ready for filter in Node.js 24.
Passing a small object of expected values is easier to read than a long arrow function with several && checks.
const where = (conditions) => (item) =>
Object.entries(conditions).every(([key, value]) => item[key] === value);
const users = [
{ name: 'Ada', role: 'admin', active: true },
{ name: 'Lin', role: 'editor', active: true },
{ name: 'Sam', role: 'admin', active: false },
];
console.log(users.filter(where({ role: 'admin', active: true })));
console.log(users.filter(where({ role: 'admin' })).length);[ { name: 'Ada', role: 'admin', active: true } ]
2where returns a function for filter. Inside it, every checks each pair of the condition object against the item, and === makes the match strict, so '1' does not equal 1. See Object.entries and every.
It handles equality only. Ranges, or and nested fields need a different shape, or a function. An empty condition object matches everything, because every on an empty array is true.