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!

3
  • 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? Commented Sep 13, 2021 at 2:35
  • You can use _isEqual from lodash for your comparison and check another methods here if you want. But I'll prefer to use _isEqual. Commented Sep 13, 2021 at 2:59
  • I advise to see these questions: First: Object comparison in JavaScript Second: How to determine equality for two JavaScript objects? Commented Sep 13, 2021 at 8:27

1 Answer 1

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);
    });
  }

 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.