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?

1

2 Answers 2

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; } 
Sign up to request clarification or add additional context in comments.

1 Comment

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 :)
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

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.