JavaScript: Compare the structure of two JSON objects while ignoring their values JavaScript: Compare the structure of two JSON objects while ignoring their values json json

JavaScript: Compare the structure of two JSON objects while ignoring their values


This is an elegant solution. You could do it simple like this:

var equal = true;for (i in object1) {    if (!object2.hasOwnProperty(i)) {        equal = false;        break;    }}

If the two elements have the same properties, then, the var equal must remain true.

And as function:

function compareObjects(object1, object2){    for (i in object1)        if (!object2.hasOwnProperty(i))            return false;    return true;}


You can do that using hasOwnProperty function, and check every property name of object1 which is or not in object2:

function hasSameProperties(obj1, obj2) {  return Object.keys(obj1).every( function(property) {    return obj2.hasOwnProperty(property);  });}

Demo