0

Folks, Given the following 2 Objects, what would be the best way to compare them, and return only the differences between them?

{ _id: 530797d8952e10129f97fde3,
  Product: 'something',
  Realm: [ 'something', 'something','foo' ],
  Service: 'Node',
  Owners: [ 'foo', 'something' ],
  Project: 'something',
  URLs:
    [ { 'foo': [Object] },
      { 'foo': [Object] },
      { 'foo': [Object] } ] }

...

{ _id: 530797d8952e10129f97fde3,
  Product: 'something',
  Realm: [ 'something', 'something','foo' ],
  Service: 'Node',
  Owners: [ 'foo', 'something' ],
  Project: 'something',
  URLs:
    [ { 'bar': [Object] },
      { 'foo': [Object] },
      { 'quux': [Object] } ] }

Should I loop through these and compare, or is there a pre-built module people use?

Thanks!

Cmag
  • 14,946
  • 25
  • 89
  • 140
  • I haven't heard of such a module. Anyway, you should also post the expected outcome of the code, the differences. – Tibos Feb 25 '14 at 20:20
  • If you just want to compare and check if they are the same, you could use underscore - `_.isEqual()` http://underscorejs.org/#isEqual You could also look into `isEqual()` source to get some idea - https://github.com/jashkenas/underscore/blob/master/underscore.js. – palanik Feb 25 '14 at 20:21
  • I'm not aware of any module that would return the difference between objects, but a simple recursive function would do. If the objects are not equals by using the `_.isEqual` as mentioned by @palanik it doesn't worth the extra step of checking.. – Gntem Feb 25 '14 at 20:59
  • Maybe you can start our with the comparison methods here: http://stackoverflow.com/questions/1068834/object-comparison-in-javascript. And build one to return an object with only the differences? – Spork Feb 25 '14 at 23:28
  • Folks, as answered below, `deep-diff` is the answer! – Cmag Feb 26 '14 at 14:23

1 Answers1

1

There is a fantastic node.js module written by flitbit that will do exactly what you desire: deep-diff.

I won't go into to much detail about it (the module page is well-written), but it will compute the difference between two objects and given you a detailed output describing it. The output includes whether a property is new/deleted or merely has a different value.

J David Smith
  • 4,780
  • 1
  • 19
  • 24