how to compare two object in javascript code example
Example 1: javascript how to compare object values
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;
}
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)
});