Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript compare objects having functions using lodash isEqual

how to compare two objects for equality if they have functions? lodash's isEqual works really well until functions are thrown in:

_.isEqual({
    a: 1,
    b: 2
}, {
    b: 2,    
    a: 1
});

// -> true

_.isEqual({
    a: 1,
    b: 2,
    c: function () {
        return 1;
    }
}, {
    a: 1,    
    b: 2,
    c: function () {
          return 1;
    }
});

// -> false
like image 918
pistacchio Avatar asked May 13 '15 10:05

pistacchio


People also ask

How do you compare objects in Lodash?

In Lodash, we can deeply compare two objects using the _. isEqual() method. This method will compare both values to determine if they are equivalent.

How does Lodash isEqual work?

The Lodash _. isEqual() Method performs a deep comparison between two values to determine if they are equivalent. This method supports comparing arrays, array buffers, boolean, date objects, maps, numbers, objects, regex, sets, strings, symbols, and typed arrays.

How can we compare two objects in JavaScript?

isEqaul is property of lodash which is used to compare JavaScript objects. It is used to know whether two objects are same or not. For ex, there are two arrays with equal number of elements, properties and values are also same. Even the properties are not in same order it will return true.


1 Answers

Try isEqualWith instead:

import { isEqualWith, isFunction } from 'lodash-es'

const o1 = { fn() {} }

const o2 = { fn() {} }

const equal = isEqualWith(o1, o2, (v1, v2) =>
  // if `customizer` returns `undefined`, comparisons are handled by the method instead
  isFunction(v1) && isFunction(v2) ? `${v1}` === `${v2}` : undefined,
)

console.log({ equal }) // { equal: true }
like image 116
Wenfang Du Avatar answered Sep 21 '22 00:09

Wenfang Du