How Lodash conformsTo Evaluates Object Properties
The _.conformsTo method in Lodash is a utility used to
validate whether an object meets specific structural and data criteria.
This article explains how _.conformsTo operates,
specifically detailing how it evaluates an object's properties against a
source schema composed of predicate functions to return a boolean
result.
How
_.conformsTo Evaluates Properties
The _.conformsTo method evaluates an object's property
values against predicate functions provided in a source
object. Instead of comparing values for direct equality (like
_.isMatch), it executes a user-defined function for each
corresponding property to determine if that property meets specific
logic.
The syntax for the method is:
_.conformsTo(object, source);The Evaluation Mechanism
- Mapping by Property Keys: Lodash iterates through
the keys present in the
sourceobject. - Executing Predicates: For each key in
source, Lodash expects the value to be a predicate function. It invokes this function, passing the targetobject's corresponding property value as an argument. - Truthy Verification: Each predicate function must
return a truthy value. If all predicate functions return truthy,
_.conformsToreturnstrue. If any predicate function returns a falsy value (or throws an error), the method immediately evaluates tofalse.
Example
const _ = require('lodash');
const user = {
name: 'Alex',
age: 28,
active: true
};
// Define predicates for properties you want to check
const userRules = {
age: (n) => n >= 18,
active: (val) => typeof val === 'boolean'
};
console.log(_.conformsTo(user, userRules)); // trueKey Behaviors to Note
- Partial Validation: The target object can have
extra properties not defined in the source validator. Lodash only tests
the properties specified in the
sourceobject. - Missing Properties: If a property exists in the
sourcevalidator but is missing on the targetobject,undefinedis passed to the predicate function. The validation will fail unless the predicate explicitly allowsundefined. - Functions Required: If a property value in the
sourceobject is not a function, the evaluation for that property will not behave as an equality check;_.conformsTostrictly expects functions as the source values.