The ways to compare 2 deep nested objects in JavaScript

There are two ways to compare 2 deep nested objects in Javascript.

Example, we will compare two deep objects bellow:

 const first = {
  name: 'first object',
  nested: {
    id: 'abc',
    nested: {
      name: 'apple',
    },
  },
};

const second = {
  name: 'first object',
  nested: {
    id: 'abc',
    nested: {
      name: 'apple',
    },
  },
};


Use JSON.stringify method::

 JSON.stringify(first) === JSON.stringify(second);
 // result is: true


The JSON.stringify method converts a JavaScript object or value to a JSON string


Using isEqual method of Lodash library

 import isEqual from 'lodash';
 
 isEqual(first, second);
 // result is: true


© 2019 4codev

Created with love by Sil.