I'm working on an API testing algorithm within the Postman REST client and I wanted a simple and elegant deep diff function to test my JSON responses. I only have access to Lodash within Postman's testing sandbox.
I couldn't find one on SO or elsewhere online so I decided to write one for myself. My goal was to write the function in less than 10 lines of code so that it is easy to copy/paste and easy to tell what is happening for future people working on the project. I actually got it to work in 5 lines!
_.merge(obj1, obj2, function (objectValue, sourceValue, key, object, source) {
if ( !(_.isEqual(objectValue, sourceValue)) && (Object(objectValue) !== objectValue)) {
console.log(key + "\n Expected: " + sourceValue + "\n Actual: " + objectValue);
}
});
Obviously you can change the console.log()
to suit your application. I don't actually use object
and source
but the variables are all there for anyone who wishes to expand this function for their own use. You could create an array of values that are different. Not bad for learning JavaScript 2 weeks ago!
If you don't want to clobber your obj1
you can do a var obj1Copy = _.cloneDeep(obj1)
and use your clone object instead.
If you want to trace down through your object from high level to low level, you can remove the && (Object(objectValue) !== objectValue)
from the if
statement.
Is there any way to improve this code?