Home > Net >  Check if two objects are equal React Native
Check if two objects are equal React Native

Time:09-17

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!

CodePudding user response:

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

 
  • Related