check if two objects are equal javascript code example
Example 1: javascript check if objects are equal
const isEqual = (...objects) => objects.every(obj => JSON.stringify(obj) === JSON.stringify(objects[0]));
isEqual({ foo: 'bar' }, { foo: 'bar' });
isEqual({ foo: 'bar' }, { bar: 'foo' });
Example 2: javascript objet keys comparaison
var myString = "Item1";
var jsObject =
{
Item1:
{
"apples": "red",
"oranges": "orange",
},
Item2:
{
"bananas": "yellow",
"pears": "green"
}
};
var keys = Object.keys(jsObject);
keys.forEach(function(key) {
console.log(key, key == myString)
});
Example 3: check if objects are equal javascript
function isEquivalent(a, b) {
var aProps = Object.getOwnPropertyNames(a);
var bProps = Object.getOwnPropertyNames(b);
if (aProps.length != bProps.length) {
return false;
}
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i];
if (a[propName] !== b[propName]) {
return false;
}
}
return true;
}
console.log(isEquivalent(bobaFett, jangoFett));