1

Can you help me on how to check if object the two objects are equal? here's the two objects that I'm trying to compare...

let obj1 = {"Add Ons": [{"addon_id": 32, "addon_name": "Black Pearl", "addon_price": 15}, {"addon_id": 33, "addon_name": "White Pearl", "addon_price": 15}]}
let obj2 = {"Add Ons": [{"addon_id": 33, "addon_name": "White Pearl", "addon_price": 15}, {"addon_id": 32, "addon_name": "Black Pearl", "addon_price": 15}]}

I tried using this const isEqual = (...objects) => objects.every(obj => JSON.stringify(obj) === JSON.stringify(objects[0])); to check if it's equal but if the array inside is shuffle it returns false. how to check if it's equal event though in random? thank you so much!

carch
  • 217
  • 4
  • 18
  • How do you identify 2 objects are different? I mean which property we can use? All of it? if any value is different it's not the same? If the same `addon_id` is present in both arrays, can we call it equal? – Sanish Joseph Sep 13 '21 at 02:35
  • You can use [_isEqual](https://lodash.com/docs#isEqual) from `lodash` for your comparison and check another methods [here](https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) if you want. But I'll prefer to use `_isEqual`. – Rohit Aggarwal Sep 13 '21 at 02:59
  • I advise to see these questions: First: [Object comparison in JavaScript](https://stackoverflow.com/questions/1068834/object-comparison-in-javascript?noredirect=1&lq=1) Second: [How to determine equality for two JavaScript objects?](https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects/16788517#16788517) – Mohamadamin Sep 13 '21 at 08:27

1 Answers1

1

Assuming you are checking for equality of addon_id,

  1. You can get the arrays like obj1['Add Ons']
  2. If the length of arrays is not the same then they are not equal.
  3. Check for all objects in the first array with every() and check whether the obj2 array contains all of the ids.
    function isEqual() {
    let obj1 = {
      'Add Ons': [
        { addon_id: 32, addon_name: 'Black Pearl', addon_price: 15 },
        { addon_id: 33, addon_name: 'White Pearl', addon_price: 15 }
      ]
    };
    let obj2 = {
      'Add Ons': [
        { addon_id: 33, addon_name: 'White Pearl', addon_price: 15 },
        { addon_id: 32, addon_name: 'Black Pearl', addon_price: 15 },
        { addon_id: 34, addon_name: 'Black Pearl', addon_price: 15 }
      ]
    };

    if (obj1['Add Ons'].length !== obj2['Add Ons']) return false;
    return obj1['Add Ons'].every(val => {
      return obj2['Add Ons'].some(b2 => b2.addon_id === val.addon_id);
    });
  }

 
Sanish Joseph
  • 2,140
  • 3
  • 15
  • 28