Deep object diff in JavaScript

An every day tool of the developer's trade is a text diff program. Most probably know of it when they are comparing two source files between commits or branches. It's also useful when you are comparing data that is structurally similar. Traditional diff tools focus on text because it is easy to compare two strings and see the changes between the two.

I recently ran into a problem where I had to compare two objects. My first instinct was just to stringify the objects and compare them as text using a diff tool. This didn't fully cover everything I had hoped to cover. Keys are not ensured to be ordered in JavaScript, so you could have two of the same objects but still show many differences. It's highly dependent on the JSON formatter you are using, so you can see extra differences if there is a line break somewhere. JSON only serializes certain values and ignores data like functions. It didn't make for a very robust solution if you wanted to be certain an object was the same or not.

Luckily, I found the deep-diff package which addresses most of these issues. The output isn't as readily apparent as doing a text diff but it provides a lot more information. It can tell you what kind of change took place, whether it is in an array, object key, or data value. It's also very useful for testing if an object equivalent to another, similar to lodash's _.isEqual.

I wrote a few test cases for that covers the basic usage. Check them out below:

Bret Lowrey

Code is like a war - the best code is one never written.

Florida, USA