json-changes

1.0.0 • Public • Published

json-changes

Easily compare changes in JSON-like values. This can be especially useful when you want to compare an incoming payload with a counterpart stored in a database.

npm version CI status

Installation

npm i json-changes

Usage

First, let's define our flags in a file we'll call permissions.js:

const diff = require('json-changes')

const before = { hello: 'world', foo: 'bar', thisPropertyNoLongerExists: true }
const after = { hello: 'world', foo: 'not bar' }

const comparison = diff(before, after)
// returns:
{
  before: {
    foo: 'bar',
    thisPropertyNoLongerExists: true
  },
  after: {
    // Only properties that changed are included
    foo: 'not bar',
    // Properties that have been removed have an undefined value;
    thisPropertyNoLongerExists: undefined
  }
}

It works recursively in nested objects as well:

const before = { nestedObj: {} }
const after = { nestedObj: { evenMoreNestedObject: { thisPropIsNew: 'Hello, new property!' } } }

const comparison = diff(before, after)
// returns:
{
  before: {
    nestedObj: { evenMoreNestedObject: undefined }
  },
  after: {
    nestedObj: {
      evenMoreNestedObject: {
        thisPropIsNew: 'Hello, new property!'
      }
    }
  }
}

undefined values

Encountering an undefined value in the comparison means that the property either did not exist in before or was removed in after.

json-changes is primarily meant to be used to compare JSON, so undefined is assumed to never be used in the payloads being compared.

Dependencies (0)

    Dev Dependencies (6)

    Package Sidebar

    Install

    npm i json-changes

    Weekly Downloads

    1

    Version

    1.0.0

    License

    MIT

    Unpacked Size

    6.24 kB

    Total Files

    5

    Last publish

    Collaborators

    • sleavely