Answers for "Javascript compare two objects"

10

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
}
Posted by: Guest on July-25-2019
4

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;
}
Posted by: Guest on April-21-2020
5

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;
}
Posted by: Guest on August-16-2020
0

compare objects

//No generic function to do that at all.
//use Lodash, famous for such must have functions, all efficiently built
//http://lodash.com/docs#isEqual --- npm install lodash

_.isEqual(object, other);
Posted by: Guest on September-01-2021
-1

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)
});
Posted by: Guest on July-12-2020

Code answers related to "Javascript compare two objects"

Code answers related to "Javascript"

Browse Popular Code Answers by Language