diff-to-patch
A function that compares two JavaScript-objects and returns an array of JSON Patch-operations representing the difference between the two objects.
Install
npm install diff-to-patch
Usage
To use the function, simply require
it and pass two objects you want to compare to it:
const diffToPatch = ; ;// => [{ op: 'replace', path: '/foo', value: 'baz' }] ;// => [{ op: 'add', path: '/foo', value: 'bar' }] ;// => [{ op: 'remove', path: '/foo' }] ;// => [{ op: 'replace', path: '/2', value: 4}] ;// => [{ op: 'add', path: '/3', value: 4}] ;// => [{ op: 'remove', path: '/2'}]
You can pass objects with arbitrary complexity:
let objA = name: 'Bob' age: 25 address: street: '468 Ash Street' city: 'Bedias, South Carolina' zipCode: '1669' phoneNumbers: '+1 (908) 493-3564' '+1 (858) 591-3751' ; let objB = name: 'Bobby' age: 26 address: street: '468 Ash Street' city: 'Bedias, South Carolina' zipCode: '1669' phoneNumbers: '+1 (908) 493-3564' email: 'bob@gmail.com' ;/* => [ { op: 'replace', path: '/name', value: 'Bobby' }, { op: 'replace', path: '/age', value: 26 }, { op: 'remove', path: '/phoneNumbers/1' }, { op: 'add', path: '/email', value: 'bob@gmail.com' } ]*/
The function validates the input arguments and throws a NoValidInputJSONError
if at least one of the input arguments...
- ...is
null
orundefined
- ...is of a primitive type (string, boolean, number)
- ...is an object that is not valid JSON (i.e. a function)
- ...contains a circular reference
- ...does not have the same type as the other input argument