object-diff

Get the diff from object A to object B

object-diff downloads object-diff version object-diff license

object-diffSimilar Packages:
Npm Package Weekly Downloads Trend
3 Years
🌟 Show real-time usage chart on object-diff's README.md, just copy the code below.
## Usage Trend
[![Usage Trend of object-diff](https://npm-compare.com/img/npm-trend/THREE_YEARS/object-diff.png)](https://npm-compare.com/object-diff#timeRange=THREE_YEARS)
Cumulative GitHub Star Trend
🌟 Show GitHub stars trend chart on object-diff's README.md, just copy the code below.
## GitHub Stars Trend
[![GitHub Stars Trend of object-diff](https://npm-compare.com/img/github-trend/object-diff.png)](https://npm-compare.com/object-diff)
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
object-diff20,867432.55 kB0a month agoMIT
README for object-diff

object diff

Get the minimal patch to extend literal object A with to transform it into literal object B

Consider an object retrieved from a server:

{
	name: 'Peter',
	age: 26,
	height: 187,
}

Now the user changes stuff using some frontend (e.g. a HTML form) and ends with:

{
	name: 'Peter',
	age: 27,
	height: 186,
}

When they hit save, you only want to send off the changed parts to the servers, to save bits (because you're indeed a programmer), but also to avoid any unnecessary "merge conflicts" at the server.

Imagine two users changing the same object; if they did not change the exact same keys of the object, the last user won't erase the first user's changes - in a lot of cases, that's the expected behavior.

Usage

import diff from 'object-diff'

const a = {
  speed: 4,
  power: 54,
  height: undefined,
  level: 1,
}

const b = {
  speed: 4, // unchanged
  power: 22, // changed
  level: undefined, // changed
  weight: 10, // added
}

diff(a, b)
/*
{
	power: 22,
	level: undefined,
	weight: 10,
}
*/

// using a custom equality function

const past = '2016-04-24T10:39:23.419Z'

import custom from 'object-diff'
custom(
  (a, b) => {
    if (a instanceof Date && b instanceof Date) {
      return a.getTime() === b.getTime()
    }
    return a === b
  },
  {
    then: new Date(past),
  },
  {
    then: new Date(past),
  },
)
/*
{}
*/

Compatibility

Versions 0.0.4 and 1.0.0 are functionally equivalent, without known issues, but are CommonJS modules and compatible with older runtimes.