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

  1. Mapping by Property Keys: Lodash iterates through the keys present in the source object.
  2. Executing Predicates: For each key in source, Lodash expects the value to be a predicate function. It invokes this function, passing the target object's corresponding property value as an argument.
  3. Truthy Verification: Each predicate function must return a truthy value. If all predicate functions return truthy, _.conformsTo returns true. If any predicate function returns a falsy value (or throws an error), the method immediately evaluates to false.

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)); // true

Key Behaviors to Note