object-diff
DefinitelyTyped icon, indicating that this package has TypeScript declarations provided by the separate @types/object-diff package

0.0.4 • Public • Published

object diff

Get the minimal patch to extend objectA with to transform it into objectB

npm version

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 he hits 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.

Install

npm install object-diff

Usage

var diff = require('object-diff');
 
var a = {
    speed: 4,
    power: 54,
    height: undefined,
    level: 1,
};
 
var 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
 
var past = '2016-04-24T10:39:23.419Z';
 
diff.custom({
    equal: dateAwareComparator,
}, {
    then: new Date(past),
}, {
    then: new Date(past),
});
/*
{}
*/
 
function dateAwareComparator( a, b ){
    if (instanceof Date && b instanceof Date)
        return a.getTime() === b.getTime();
 
    return a === b;
}
 

License

MIT © src.agency / Thomas Jensen

Readme

Keywords

Package Sidebar

Install

npm i object-diff

Weekly Downloads

8,941

Version

0.0.4

License

MIT

Last publish

Collaborators

  • thomas-jensen