Search code examples
javascriptangulartypescriptlodash

Lodash - Show changed properties of object


I have a comparison function that checks if the user has changed any property values in the objects like this.

private checkForChanges(): boolean {
    if (_.isEqual(this.definitionDetails, this.originalDetails) === true) {
        return false;
    } else {
        return true;
    }
}

this works great, however now I want to console.log changes which property is changed if there are any changes.

I've tried this:

console.log(_.difference(_.keys(this.originalDetails), _.keys(this.definitionDetails)));

but I always get [] so I assume my syntax is wrong.

What's the correct way to achieve what I want?


Solution

  • The _.isEqual might return false if the values changed, this can happen even if the keys stayed the same.

    For example: {x: 11, y: 12}, and {x: 11, y: 13} will return false though they still have the same keys.

    Your _.difference() compares the keys.

    To get the keys that changed you'll need to implement your own function:

    function changedKeys(o1, o2) {
      var keys = _.union(_.keys(o1), _.keys(o2));
      return _.filter(keys, function(key) {
        return o1[key] !== o2[key];
      });
    }