close

How to do a deep comparison between 2 objects with lodash?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to do a deep comparison between 2 objects with lodash? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to do a deep comparison between 2 objects with lodash ?

  1. How to do a deep comparison between 2 objects with lodash ?

    do a deep comparison between 2 objects with lodash Here is a simple Typescript with Lodash deep difference checker which will produce a new object with just the differences between an old object and a new object.

  2. do a deep comparison between 2 objects with lodash

    do a deep comparison between 2 objects with lodash Here is a simple Typescript with Lodash deep difference checker which will produce a new object with just the differences between an old object and a new object.

Method 1

If you need to know which properties are different, use reduce():

_.reduce(a, function(result, value, key) {
    return _.isEqual(value, b[key]) ?
        result : result.concat(key);
}, []);
// → [ "prop2" ]

Method 2

Here is a simple Typescript with Lodash deep difference checker which will produce a new object with just the differences between an old object and a new object.

For example, if we had:

const oldData = {a: 1, b: 2};
const newData = {a: 1, b: 3};

the resulting object would be:

const result: {b: 3};

It is also compatible with multi-level deep objects, for arrays it may need some tweaking.

import * as _ from "lodash";

export const objectDeepDiff = (data: object | any, oldData: object | any) => {
  const record: any = {};
  Object.keys(data).forEach((key: string) => {
    // Checks that isn't an object and isn't equal
    if (!(typeof data[key] === "object" && _.isEqual(data[key], oldData[key]))) {
      record[key] = data[key];
    }
    // If is an object, and the object isn't equal
    if ((typeof data[key] === "object" && !_.isEqual(data[key], oldData[key]))) {
      record[key] = objectDeepDiff(data[key], oldData[key]);
    }
  });
  return record;
};

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment