3
\$\begingroup\$

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?

\$\endgroup\$
1
\$\begingroup\$

Two things could be improved, otherwise it looks good:

  1. _.isEqual alone should be enough for an equality check, i.e. the check for object equality is implied.
  2. console.log might not be available.
\$\endgroup\$
  • 1
    \$\begingroup\$ 1. It sure is! I'm using the Object equality check because I don't want nested objects being printed to the console, only the endpoint where the difference occurs. Although, for large objects with internal objects, this may be helpful if things are named the same (such as an array of similar objects). \$\endgroup\$ – toshiomagic Jun 17 '15 at 21:47
  • 1
    \$\begingroup\$ 2. That's fine. console.log is available for me and the intent is for people to use this for their own purposes. If console.log isn't available then you can do something else like use the fs library or nothing at all. \$\endgroup\$ – toshiomagic Jun 17 '15 at 21:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.