I am using _.isEqual that compares 2 array of objects (ex:10 properties each object), and it is working fine.
Now there are 2 properties (creation and deletion) that i need not to be a part of comparison.
Example:
var obj1 = {name: "James", age: 17, creation: "13-02-2016", deletion: "13-04-2016"} var obj2 = {name: "Maria", age: 17, creation: "13-02-2016", deletion: "13-04-2016"} // lodash method... _.isEqual(firstArray, secondArray)
The Lodash _. unset() method is used to remove the property at the path of the object. If the property is removed then it returns True value otherwise, it returns False.
The Lodash _. isEqual() Method performs a deep comparison between two values to determine if they are equivalent.
In Lodash, we can deeply compare two objects using the _. isEqual() method. This method will compare both values to determine if they are equivalent.
Overview. The _. get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.
You can use omit() to remove specific properties in an object.
var result = _.isEqual( _.omit(obj1, ['creation', 'deletion']), _.omit(obj2, ['creation', 'deletion']) );
var obj1 = { name: "James", age: 17, creation: "13-02-2016", deletion: "13-04-2016" }; var obj2 = { name: "Maria", age: 17, creation: "13-02-2016", deletion: "13-04-2016" }; var result = _.isEqual( _.omit(obj1, ['creation', 'deletion']), _.omit(obj2, ['creation', 'deletion']) ); console.log(result);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
@ryeballar's answer is not great for large objects because you are creating a deep copy of each object every time you do the comparison.
It's better to use isEqualWith
. For example, to ignore differences in the "creation" and "deletion" properties:
var result = _.isEqualWith(obj1, obj2, (value1, value2, key) => { return key === "creation" || key === "deletion" ? true : undefined; });
EDIT (important caveat pointed out in the comments): if objects have different numbers of keys, then isEqualWith
considers them to be different, regadless of what your customizer does. Therefore do not use this approach if you want to ignore an optional property. Instead, consider using _.isMatch()
, _.isMatchWith()
, or @ryeballar's _.omit()
approach.
Note that if you're writing for ES5 and earlier, you'll have to replace the arrow syntax (() => {
) with function syntax (function() {
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With