Skip to content
jshacks.dev
Functions

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.

1 min read
Summarize in AI

Passing a small object of expected values is easier to read than a long arrow function with several && checks.

JavaScript
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);
Text
[ { name: 'Ada', role: 'admin', active: true } ]
2

where 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.

Taggednode 24
Share

More snippets

Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.