compare two objects in javascript code example

Example 1: Javascript compare two objects

var person1={first_name:"bob"};
var person2 = {first_name:"bob"}; 

//compare the two object
if(JSON.stringify(person1) === JSON.stringify(person2)){
    //objects are the same
}

Example 2: javascript how to compare object values

function isEquivalent(a, b) {
    // Create arrays of property names
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);

    // If number of properties is different,
    // objects are not equivalent
    if (aProps.length != bProps.length) {
        return false;
    }

    for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i];

        // If values of same property are not equal,
        // objects are not equivalent
        if (a[propName] !== b[propName]) {
            return false;
        }
    }

    // If we made it this far, objects
    // are considered equivalent
    return true;
}

Example 3: how to compare javascript objects

function shallowEqual(object1, object2) {
  const keys1 = Object.keys(object1);
  const keys2 = Object.keys(object2);

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

  for (let key of keys1) {
    if (object1[key] !== object2[key]) {
      return false;
    }
  }

  return true;
}

Example 4: javascript objet keys comparaison

var myString = "Item1";

var jsObject = 
{
    Item1:
    {
        "apples": "red",
        "oranges": "orange",
    },
    Item2:
    {
        "bananas": "yellow",
        "pears": "green"
    }
};

var keys = Object.keys(jsObject); //get keys from object as an array

keys.forEach(function(key) { //loop through keys array
  console.log(key, key == myString)
});