Search code examples
javascriptjsoncomparison

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?


Solution

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