JSFiddle - React, Tailwind, and code Playground

by hamzeen hameem

JavaScript

const obj1 = {
  "user": {
    "name": "max",
    "work": {
      "position": "accountant"
    }
  }
}

const obj2 = {
  "user": {
    "work": {
      "position": "accountant"
    },
    "name": "max"
  }
}

function deepEqual(obj1, obj2) {
    if (obj1 === obj2) return true; // If both are null or same reference
    
    if (typeof obj1 !== 'object' || typeof obj2 !== 'object' || obj1 === null || obj2 === null) {
        return false;
    }

    let keys1 = Object.keys(obj1);
    let keys2 = Object.keys(obj2);

    if (keys1.length !== keys2.length) {
        return false;
    }

    for (let key of keys1) {
        if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) {
            return false;
        }
    }

    return true;
}


const isEqual1 = JSON.stringify(obj1) === JSON.stringify(obj2);
console.log("shallow:: is equal:" + isEqual1);

const isEqual2 = deepEqual(obj1, obj2);
console.log("deep:: is equal:" + isEqual2);