Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax: 
3.2.
Parameters:
3.3.
Return Value:
4.
Examples 
4.1.
Validating Object Properties:
4.2.
JavaScript
4.3.
Conditional Processing Based on Object Shape:
4.4.
JavaScript
4.5.
Filtering a Collection of Objects:
4.6.
JavaScript
4.7.
Combining Predicates for Complex Conditions:
4.8.
JavaScript
5.
Frequently Asked Questions
5.1.
What types of predicates can be used with _.conformsTo()?
5.2.
Does _.conformsTo() check for properties not defined in the specification?
5.3.
Can _.conformsTo() handle nested objects?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.conformsTo() Method

Introduction

Ensuring that objects meet specific criteria is a common requirement in programming, especially in scenarios involving validation or conditional processing. Lodash's _.conformsTo() method provides a straightforward way to check if an object conforms to a given specification. 

Lodash _.conformsTo() Method

This method is particularly useful for validating object shapes and properties against a set of predicate functions.

Why This Function is Used

The _.conformsTo() function is used to validate whether an object matches a specified structure or criteria. This method is beneficial when you need to check if an object meets certain conditions, such as having properties with specific values or types. It simplifies the process of validation by allowing you to define a specification as an object where each key-value pair represents a property and a predicate function for validation.

Syntax, Parameter and Return Value

Syntax: 

_.conformsTo(object, source)

Parameters:

  • object (Object): The object to inspect.
     
  • source (Object): The object of property predicates to conform to.

Return Value:

 (boolean) - Returns true if object conforms, else false.

Examples 

Validating Object Properties:

  • JavaScript

JavaScript

var _ = require('lodash');

var object = { a: 1, b: 'string' };

var predicates = {

 a: _.isNumber,

 b: _.isString

};

console.log(_.conformsTo(object, predicates));
You can also try this code with Online Javascript Compiler
Run Code

Output: 

true


Demonstrates checking if an object's properties match the specified types.

Conditional Processing Based on Object Shape:

  • JavaScript

JavaScript

function processObject(obj) {

 var spec = { id: _.isNumber, name: _.isString };

 if (_.conformsTo(obj, spec)) {

   console.log('Object is valid:', obj);

 } else {

   console.error('Invalid object:', obj);

 }

}

processObject({ id: 123, name: 'Alice' }); // Object is valid

processObject({ id: '123', name: 'Alice' }); // Invalid object
You can also try this code with Online Javascript Compiler
Run Code


Shows using _.conformsTo() for conditional processing based on object validation.

Filtering a Collection of Objects:

  • JavaScript

JavaScript

var users = [

 { name: 'John', age: 25 },

 { name: 'Jane', age: '25' }

];

var isValidUser = { name: _.isString, age: _.isNumber };

var validUsers = _.filter(users, user => _.conformsTo(user, isValidUser));

console.log(validUsers);
You can also try this code with Online Javascript Compiler
Run Code

Output: 

[{ name: 'John', age: 25 }]


An example of filtering objects in a collection that meet specific criteria.

Combining Predicates for Complex Conditions:

  • JavaScript

JavaScript

var item = { quantity: 10, price: 5.99 };

var isValidItem = {

 quantity: q => _.isNumber(q) && q > 0,

 price: _.isNumber

};

console.log(_.conformsTo(item, isValidItem));
You can also try this code with Online Javascript Compiler
Run Code

 Output: 

true


Demonstrates combining predicates for more complex validation conditions.

Frequently Asked Questions

What types of predicates can be used with _.conformsTo()?

Any function that returns a boolean can be used as a predicate in _.conformsTo(). This includes Lodash's utility functions like _.isNumber, custom functions, or even native JavaScript methods.

Does _.conformsTo() check for properties not defined in the specification?

_.conformsTo() only checks for the conformity of properties defined in the specification. Properties in the object that are not in the specification are ignored.

Can _.conformsTo() handle nested objects?

_.conformsTo() is designed for top-level properties. For nested objects, you would need to create a custom predicate function to handle the nested validation.

Conclusion

Lodash's _.conformsTo() method is a concise and effective way to validate objects against a set of criteria. It simplifies the process of ensuring that objects meet specific requirements, making it a valuable tool for validation and conditional logic in a wide range of applications.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass