7

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?

jhadenfeldt
  • 194
  • 2
  • 13
  • I think this post may help you: http://stackoverflow.com/questions/1068834/object-comparison-in-javascript Best regards – UBEX May 23 '14 at 10:08

2 Answers2

3

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;
}
  • This will return true if object2 has a property than object1 doesn't have. You can do the full check with `compareObjects(object1, object2) && compareObjects(object2,object1)` but it's not so elegant. I guess there is best solution now in 2022 but I don't know yet :) – Flows Mar 22 '22 at 08:42
0

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

Getz
  • 3,983
  • 6
  • 35
  • 52
  • 4
    That is a good starting point. The problem here is that it doesn't work for nested objects or arrays. I extended your solution for nested objects, but there are still issues with arrays in case they have different lengths: [Demo](http://jsfiddle.net/FLPC9/2/) – jhadenfeldt May 23 '14 at 11:54