skip to Main Content

I have 2 different data storages which have same data stored in them. I want to check if both of them are similar. The type of data is

const object1 = {
  "name": "John",
  "age": "30",
  "height": "180 cm",
  "standard": "10th"
}

it should consider the data same even if the order of the data in the object is changed.

I have tried to generate the hash of the data and in batches and then check for their equality. But still as the input data is large it is still not a feasible way.

I want a efficient solution for the problem.

2

Answers


  1. You can do it that way

    function objectsAreEqual(obj1, obj2) {
      const keys1 = Object.keys(obj1);
      const keys2 = Object.keys(obj2);
    
      if (keys1.length !== keys2.length) {
        return false;
      }
    
      for (let key of keys1) {
        if (!obj2.hasOwnProperty(key) || obj1[key] !== obj2[key]) {
          return false;
        }
      }
    
      return true;
    }
    
    const object1 = {
      "name": "John",
      "age": "30",
      "height": "180 cm",
      "standard": "10th"
    };
    
    const object2 = {
      "standard": "10th",
      "age": "30",
      "name": "John",
      "height": "180 cm"
    };
    
    console.log(objectsAreEqual(object1, object2)); 
    
    Login or Signup to reply.
  2. I think you can try this :

    console.log(JSON.stringify(object1).split("").sort().join("") === JSON.stringify(object2).split("").sort().join("")); ```
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search