Search code examples
javascriptangularjsconstructorlodash

Lodash isEqual fails because of constructor defined by angular


I am using Lodash _.isEqual to deep-compare a local javascript object with another javascript object retrieved through angular $get.

This code says that the objects are different:

$get({...}, function (data) {

  cleanupAngularProps(data);

  if (_.isEqual(data, {name: 'Someone'}) {
    ...
  }
});

but chaging it a little as follows it now says that they are equal (as expected):

$get({...}, function (data) {

  cleanupAngularProps(data);

  if (_.isEqual(JSON.parse(JSON.stringify(data)), {name: 'Someone'}) {
    ...
  }
});

I debugged into the Lodash code and it seems to fail because both objects have different constructors.

How can I solve this without cloning the data?


Solution

  • I know this question is three years old at this point, but I have found what I believe is a more acceptable answer. Simply exclude the prototype comparison between the two objects:

    var result = _.isEqual(
      _.omit(data, ['__proto__']),
      _.omit({name: 'Someone'}, ['__proto__'])
    );