jhadenfeldt
jhadenfeldt

Reputation: 194

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

I use a Node.js based mock server for specifying and mocking API responses from a backend. It would greatly help to have some kind of check if both backend and frontend comply with the specification. In order to do that, I need some kind of method of comparing the structure of two JSON Objects.

For example those two objects should be considered equal:

var object1 = {
    'name': 'foo',
    'id': 123,
    'items' : ['bar', 'baz']
}

var object2 = {
    'name': 'bar',
    'items' : [],
    'id': 234
}

Any ideas how I would go about that?

Upvotes: 7

Views: 6842

Answers (2)

MasqueradeCircus
MasqueradeCircus

Reputation: 854

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;
}

Upvotes: 3

Getz
Getz

Reputation: 4053

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

Upvotes: 0

Related Questions