jquery-objectdiff — a jQuery plugin for comparing objects

I recently worked on a javascript project that involved a sim­ple work­flow where an unpriv­i­leged could request changes to cer­tain bits of enter­prise data. The requested changes would then route to a priv­i­leged user who would either make the requested changes or deny the request. I wanted to pro­vide a some kind of diff to the priv­i­leged user so they didn’t have to com­pare two sets of data and man­u­ally find the changes. It’s 2011—no human should ever have to man­u­ally per­form a diff!

In Rails, I’d be able to reflect on the ActiveRecord::Dirty::changes hash to see which attrib­utes were mod­i­fied and their before and after val­ues. I love how it works and I searched for a javascript diff’er that did some­thing sim­i­lar. There are a few out there, but none worked quite like I wanted, so I decided to roll my own. object­D­iff() will recur­sively com­pare two javascript objects and return an ActiveRecord-style changes object. Check it:

Usage

Sup­pose you have two javascript objects (like seri­al­ized form data):

var before = {
  "id": 123,
  "name": {
    "first": "Johnny",
    "last":"Johnson"
  }
};

var after = {
  "id": 123,
  "name": {
    "first": "John",
    "last": "Johnson"
  },
  "age": 30
};

A call to objectDiff(before, after) would return an object of only the changes:


{"name": {"first": ["Johnny", "John"]}, "age": [null, 30]}

I hope this is use­ful to some­one. It’s wrapped up in a jQuery plu­gin on Github: jquery-objectdiff.

Comment on this post

You may use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>