Git Product home page Git Product logo

diff's Introduction

deep-diff

CircleCI

NPM

deep-diff is a javascript/node.js module providing utility functions for determining the structural differences between objects and includes some utilities for applying differences across objects.

Install

npm install deep-diff

Possible v1.0.0 incompatabilities:

  • elements in arrays are now processed in reverse order, which fixes a few nagging bugs but may break some users
    • If your code relied on the order in which the differences were reported then your code will break. If you consider an object graph to be a big tree, then deep-diff does a pre-order traversal of the object graph, however, when it encounters an array, the array is processed from the end towards the front, with each element recursively processed in-order during further descent.

Features

  • Get the structural differences between two objects.
  • Observe the structural differences between two objects.
  • When structural differences represent change, apply change from one object to another.
  • When structural differences represent change, selectively apply change from one object to another.

Installation

npm install deep-diff

Importing

nodejs

var diff = require('deep-diff')
// or:
// const diff = require('deep-diff');
// const { diff } = require('deep-diff');
// or:
// const DeepDiff = require('deep-diff');
// const { DeepDiff } = require('deep-diff');
// es6+:
// import diff from 'deep-diff';
// import { diff } from 'deep-diff';
// es6+:
// import DeepDiff from 'deep-diff';
// import { DeepDiff } from 'deep-diff';

browser

<script src="https://cdn.jsdelivr.net/npm/deep-diff@1/dist/deep-diff.min.js"></script>

In a browser, deep-diff defines a global variable DeepDiff. If there is a conflict in the global namespace you can restore the conflicting definition and assign deep-diff to another variable like this: var deep = DeepDiff.noConflict();.

Simple Examples

In order to describe differences, change revolves around an origin object. For consistency, the origin object is always the operand on the left-hand-side of operations. The comparand, which may contain changes, is always on the right-hand-side of operations.

var diff = require('deep-diff').diff;

var lhs = {
  name: 'my object',
  description: 'it\'s an object!',
  details: {
    it: 'has',
    an: 'array',
    with: ['a', 'few', 'elements']
  }
};

var rhs = {
  name: 'updated object',
  description: 'it\'s an object!',
  details: {
    it: 'has',
    an: 'array',
    with: ['a', 'few', 'more', 'elements', { than: 'before' }]
  }
};

var differences = diff(lhs, rhs);

v 0.2.0 and above The code snippet above would result in the following structure describing the differences:

[ { kind: 'E',
    path: [ 'name' ],
    lhs: 'my object',
    rhs: 'updated object' },
  { kind: 'E',
    path: [ 'details', 'with', 2 ],
    lhs: 'elements',
    rhs: 'more' },
  { kind: 'A',
    path: [ 'details', 'with' ],
    index: 3,
    item: { kind: 'N', rhs: 'elements' } },
  { kind: 'A',
    path: [ 'details', 'with' ],
    index: 4,
    item: { kind: 'N', rhs: { than: 'before' } } } ]

Differences

Differences are reported as one or more change records. Change records have the following structure:

  • kind - indicates the kind of change; will be one of the following:
    • N - indicates a newly added property/element
    • D - indicates a property/element was deleted
    • E - indicates a property/element was edited
    • A - indicates a change occurred within an array
  • path - the property path (from the left-hand-side root)
  • lhs - the value on the left-hand-side of the comparison (undefined if kind === 'N')
  • rhs - the value on the right-hand-side of the comparison (undefined if kind === 'D')
  • index - when kind === 'A', indicates the array index where the change occurred
  • item - when kind === 'A', contains a nested change record indicating the change that occurred at the array index

Change records are generated for all structural differences between origin and comparand. The methods only consider an object's own properties and array elements; those inherited from an object's prototype chain are not considered.

Changes to arrays are recorded simplistically. We care most about the shape of the structure; therefore we don't take the time to determine if an object moved from one slot in the array to another. Instead, we only record the structural differences. If the structural differences are applied from the comparand to the origin then the two objects will compare as "deep equal" using most isEqual implementations such as found in lodash or underscore.

Changes

When two objects differ, you can observe the differences as they are calculated and selectively apply those changes to the origin object (left-hand-side).

var observableDiff = require('deep-diff').observableDiff;
var applyChange = require('deep-diff').applyChange;

var lhs = {
  name: 'my object',
  description: 'it\'s an object!',
  details: {
    it: 'has',
    an: 'array',
    with: ['a', 'few', 'elements']
  }
};

var rhs = {
  name: 'updated object',
  description: 'it\'s an object!',
  details: {
    it: 'has',
    an: 'array',
    with: ['a', 'few', 'more', 'elements', { than: 'before' }]
  }
};

observableDiff(lhs, rhs, function (d) {
  // Apply all changes except to the name property...
  if (d.path[d.path.length - 1] !== 'name') {
    applyChange(lhs, rhs, d);
  }
});

API Documentation

A standard import of var diff = require('deep-diff') is assumed in all of the code examples. The import results in an object having the following public properties:

  • diff(lhs, rhs[, options, acc]) — calculates the differences between two objects, optionally using the specified accumulator.
  • observableDiff(lhs, rhs, observer[, options]) — calculates the differences between two objects and reports each to an observer function.
  • applyDiff(target, source, filter) — applies any structural differences from a source object to a target object, optionally filtering each difference.
  • applyChange(target, source, change) — applies a single change record to a target object. NOTE: source is unused and may be removed.
  • revertChange(target, source, change) reverts a single change record to a target object. NOTE: source is unused and may be removed.

diff

The diff function calculates the difference between two objects.

Arguments

  • lhs - the left-hand operand; the origin object.
  • rhs - the right-hand operand; the object being compared structurally with the origin object.
  • options - A configuration object that can have the following properties:
    • prefilter: function that determines whether difference analysis should continue down the object graph. This function can also replace the options object in the parameters for backward compatibility.
    • normalize: function that pre-processes every leaf of the tree.
  • acc - an optional accumulator/array (requirement is that it have a push function). Each difference is pushed to the specified accumulator.

Returns either an array of changes or, if there are no changes, undefined. This was originally chosen so the result would be pass a truthy test:

var changes = diff(obja, objb);
if (changes) {
  // do something with the changes.
}

Pre-filtering Object Properties

The prefilter's signature should be function(path, key) and it should return a truthy value for any path-key combination that should be filtered. If filtered, the difference analysis does no further analysis of on the identified object-property path.

const diff = require('deep-diff');
const assert = require('assert');

const data = {
  issue: 126,
  submittedBy: 'abuzarhamza',
  title: 'readme.md need some additional example prefilter',
  posts: [
    {
      date: '2018-04-16',
      text: `additional example for prefilter for deep-diff would be great.
      https://stackoverflow.com/questions/38364639/pre-filter-condition-deep-diff-node-js`
    }
  ]
};

const clone = JSON.parse(JSON.stringify(data));
clone.title = 'README.MD needs additional example illustrating how to prefilter';
clone.disposition = 'completed';

const two = diff(data, clone);
const none = diff(data, clone,
  (path, key) => path.length === 0 && ~['title', 'disposition'].indexOf(key)
);

assert.equal(two.length, 2, 'should reflect two differences');
assert.ok(typeof none === 'undefined', 'should reflect no differences');

Normalizing object properties

The normalize's signature should be function(path, key, lhs, rhs) and it should return either a falsy value if no normalization has occured, or a [lhs, rhs] array to replace the original values. This step doesn't occur if the path was filtered out in the prefilter phase.

const diff = require('deep-diff');
const assert = require('assert');

const data = {
  pull: 149,
  submittedBy: 'saveman71',
};

const clone = JSON.parse(JSON.stringify(data));
clone.issue = 42;

const two = diff(data, clone);
const none = diff(data, clone, {
  normalize: (path, key, lhs, rhs) => {
    if (lhs === 149) {
      lhs = 42;
    }
    if (rhs === 149) {
      rhs = 42;
    }
    return [lsh, rhs];
  }
});

assert.equal(two.length, 1, 'should reflect one difference');
assert.ok(typeof none === 'undefined', 'should reflect no difference');

observableDiff

The observableDiff function calculates the difference between two objects and reports each to an observer function.

Argmuments

  • lhs - the left-hand operand; the origin object.
  • rhs - the right-hand operand; the object being compared structurally with the origin object.
  • observer - The observer to report to.
  • options - A configuration object that can have the following properties:
    • prefilter: function that determines whether difference analysis should continue down the object graph. This function can also replace the options object in the parameters for backward compatibility.
    • normalize: function that pre-processes every leaf of the tree.

Contributing

When contributing, keep in mind that it is an objective of deep-diff to have no package dependencies. This may change in the future, but for now, no-dependencies.

Please run the unit tests before submitting your PR: npm test. Hopefully your PR includes additional unit tests to illustrate your change/modification!

When you run npm test, linting will be performed and any linting errors will fail the tests... this includes code formatting.

Thanks to all those who have contributed so far!

diff's People

Contributors

amilajack avatar caasi avatar cpcallen avatar danielspangler avatar drinks avatar gautiermichelin avatar hyandell avatar icesoar avatar ioxua avatar jongwookyi avatar jsfuchs avatar kidkarolis avatar matsbryntse avatar mortonfox avatar orlando80 avatar paulpflug avatar ravishivt avatar saveman71 avatar sberan avatar serkanserttop avatar simenb avatar socalnick avatar stevemao avatar tdebarochez avatar thiamsantos avatar tmcw avatar willbiddy avatar wooorm avatar xanderberkein avatar zaubernerd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

diff's Issues

Edit the right hand of a diff before applying changes

Hi @flitbit,

thank you very much for this amazing library. It is very helpful. Would it be possible by any chance to edit the right hand of a diff before applying the changes?

// the idea was to overwrite the changes that would be applied dynamically
var observableDiff = require('deep-diff').observableDiff;
var applyChange = require('deep-diff').applyChange;

var customData = 'some custom data to be inserted';

observableDiff(existingData, newData, function (d) {

  // apply some custom data instead of the data from the right hand side
  if (d.path.join('.') == 'id.previous') {
     d.rhs = customData;
  }

  applyChange(existingData, newData, d);   
}

Path param in prefilter function is not useful

The prefilter function often passes an empty path. This param should include the entire path of where the key param exists in the JSON tree. The current empty or one level path is not enough info to make a decision on whether to filter the diff.

Apply a diff?

Is it possible to apply the results of a diff to an object?

for example:

var myDiff = diff(jsonA, jsonB);
applyDiff(myDiff, jsonBcopy); // this is what I am wondering

I know it appears unnecessary to do this, but I am comparing local files, then applying changes on a server to avoid excessively large file transfers.

Different classes

Hi,

deepDiff.diff({}, []) shows difference but this doesn't:

function A() {}

var a = new A();
var b = {};

deepDiff.diff(a, b)

I think it would be reasonable to consider two objects of different classes as different - just as we consider [] to be different from {}.

Is it a bug, negligence or deliberate move?

deep-diff does not handle cycles

Great library! Turns out this is (almost) exactly the kind of thing I was looking for to build an optimized undo framework for my app. Sadly, I won't be able to use it since it appears deep-diff does not handle cycles:

See https://tonicdev.com/0x24a537r9/deep-diff-test for an example.

Clearly some sort of cycle detection is implemented, otherwise this would trigger an infinite loop. But I see no reason why diffs could not be provided in this case for the non-cyclical level.

What's the license of this package?

You've created a very nice library. I would like to use it but i've not found under what license is it distributed?
Can you please write somewhere (readme or package.json or LICENSE file?) the license on which is it distributed. MIT license would be perfect.

Object.create(null) causes error

When diffing objects that are created using Object.create(null), DeepDiff throws an exception.

require('deep-diff')(Object.create(null), {});
// => TypeError: undefined is not a function
require('deep-diff')({}, Object.create(null));
// => TypeError: undefined is not a function

Stack:

    at realTypeOf (node_modules/deep-diff/index.js:132:39)
    at deepDiff (node_modules/deep-diff/index.js:155:36)
    at accumulateDiff (node_modules/deep-diff/index.js:202:5)
    ...

diff of equal objects should return empty array

Why does diff({}, {a: 4}) return an array of differences, but diff({}, {}) return undefined? I would expect it to return [] instead.

This makes iteration over the changes much easier. No check for undefined is needed.

We also occasionally use diff only to count the number of differences. This means code like diff(a, b).length will break on equal objects.

Non-function toString will cause crash

var deepDiff = require('deep-diff');

var left = {
  left: 'yes',
  right: 'no',
};

var right = {
  left: {
    toString: true,
  },
  right: 'no',
};

console.log(deepDiff(left, right));

Results in this:

node_modules/deep-diff/index.js:134
    } else if (typeof subject.toString !== 'undefined' && /^\/.*\//.test(subject.toString())) {
                                                                                 ^

TypeError: subject.toString is not a function
    at realTypeOf (node_modules/deep-diff/index.js:134:82)
    at deepDiff (node_modules/deep-diff/index.js:174:36)
    at node_modules/deep-diff/index.js:200:15
    at Array.forEach (native)
    at deepDiff (node_modules/deep-diff/index.js:197:17)
    at accumulateDiff (node_modules/deep-diff/index.js:221:5)
    at Object.<anonymous> (test.js:16:13)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)

I encountered this when comparing two loaded eslint configs. The set of globals did include a non-function toString key. So this really does sometimes happen! :0)

TypeError: changes is not a function

Running Node v6 on Ubuntu 14.04 LTS. Figured this may have been an issue with newest release not being pushed to NPM, but I used a git dependency and referenced the newest release, got the same error. Upon looking at the code, I cannot say I understand what is attempting to be done here, or why changes is referenced as a function at any point.

Line 140
function deepDiff(lhs, rhs, changes, prefilter, path, key, stack) {

Line 192
changes(new DiffArray(currentPath, i, new DiffNew(undefined, rhs[i++])));

Then, it appears to be self-referencial and recursively looping, which makes sense considering the nature of this module. However, I fail to see where or how changes is a function.

I'm at a loss on this one, I always prefer to try and figure these kinds of things out on my own, but I've read and re-read documentation, and the code has me flummoxed :(

Diff Running
/vagrant/node_modules/deep-diff/index.js:192
            changes(new DiffArray(currentPath, i, new DiffNew(undefined, rhs[i++])));
            ^

TypeError: changes is not a function
    at deepDiff (/vagrant/node_modules/deep-diff/index.js:192:13)
    at blocks_analyze_diff (/vagrant/app.js:214:18)
    at Timeout.worker_block_content_analyze [as _repeat] (/vagrant/app.js:182:3)
    at Timeout.wrapper [as _onTimeout] (timers.js:417:11)
    at tryOnTimeout (timers.js:224:11)
    at Timer.listOnTimeout (timers.js:198:5)

TypeError thrown with null values

TypeError: Object.keys called on non-object
at Function.keys (native)
at deepDiff (/Users/nick/src/pac12-scores/node_modules/deep-diff/lib/diff.js:84:26)
at /Users/nick/src/pac12-scores/node_modules/deep-diff/lib/diff.js:89:9
at Array.forEach (native)
at deepDiff (/Users/nick/src/pac12-scores/node_modules/deep-diff/lib/diff.js:86:13)

get list of changed items?

Hi,

I need to get just a simple list of the items that have been changed or added in an array, without any other information.

A = [ {a: 1}, {a: 2} ]
B = [ {a: 3}, {a: 2} ]

=> [ {a: 3} ]

How can I achieve it?

Uncaught TypeError: subject.toString is not a function

function realTypeOf(subject) {
        var type = typeof subject;
        if (type !== 'object') {
          return type;
        }

        if (subject === Math) {
          return 'math';
        } else if (subject === null) {
          return 'null';
        } else if (Array.isArray(subject)) {
          return 'array';
        } else if (subject instanceof Date) {
          return 'date';
        } else if (/^\/.*\//.test(subject.toString())) { // error is here
          return 'regexp';
        }
        return 'object';
      }

I'm comparing two equal objects

as you can see below - I do not have regex in my objects.
This is JSON.stringify console.log of object:

{"add_slot-0":{"branch":"add_slot-0","tagName":"h1","className":"mh tac bold ttu","branches":false,"leaf":"Add new Slot to the Dashboard"},"add_slot-1":{"branch":"add_slot-1","tagName":"button","className":"cmw pa","attributes":{"id":"cmw"},"dataset":{"hideM":true,"hideT":true},"branches":true,"leaf":false},"add_slot-1-0":{"branch":"add_slot-1-0","tagName":"svg","attributes":{"viewBox":"0 0 13 13","preserveAspectRatio":"xMinYMin slice"},"branches":true,"leaf":false},"add_slot-1-0-0":{"branch":"add_slot-1-0-0","tagName":"use","attributes":{"xlink":"#cross"},"branches":false,"leaf":false},"add_slot-2":{"branch":"add_slot-2","tagName":"div","className":"mirow ma","branches":true,"leaf":false},"add_slot-2-0":{"branch":"add_slot-2-0","tagName":"input","className":"mi db ma rd t-rd bold","attributes":{"type":"text","id":"_nm","placeholder":"New slot name"},"branches":false,"leaf":false},"add_slot-3":{"branch":"add_slot-3","tagName":"div","className":"merow ma","branches":true,"leaf":false},"add_slot-3-0":{"branch":"add_slot-3-0","tagName":"p","className":"me blue bold tac","branches":false,"leaf":"*Use full URL: ( https://domain.com/path/route ) for precise monitoring!"},"add_slot-4":{"branch":"add_slot-4","tagName":"div","className":"mirow ma","branches":true,"leaf":false},"add_slot-4-0":{"branch":"add_slot-4-0","tagName":"input","className":"mi db ma rd t-rd bold","attributes":{"type":"text","id":"_url","placeholder":"New slot URL"},"branches":false,"leaf":false},"add_slot-5":{"branch":"add_slot-5","tagName":"div","className":"merow ma","branches":true,"leaf":false},"add_slot-5-0":{"branch":"add_slot-5-0","tagName":"p","className":"me orange bold tac ma","attributes":{"id":"errorOut"},"dataset":{"hide":true},"branches":false,"leaf":""},"add_slot-6":{"branch":"add_slot-6","tagName":"div","className":"mirow ma","branches":true,"leaf":false},"add_slot-6-0":{"branch":"add_slot-6-0","tagName":"button","className":"m_btn rd t-rd bold pr centered","attributes":{"id":"_surl","disabled":true},"dataset":{"disable":"on"},"branches":false,"leaf":"Save"},"add_slot-7":{"branch":"add_slot-7","tagName":"div","className":"mirow ma","branches":true,"leaf":false},"add_slot-7-0":{"branch":"add_slot-7-0","tagName":"button","className":"mcancel blue ma rd tdu tti","attributes":{"id":"mcancel"},"dataset":{"hideM":"true"},"branches":false,"leaf":"Cancel"}}

Comparing objects with longer cycles.

Hi,

comparing objects with such cycles doesn't work:

var deepDiff = require("deep-diff");

var a = {prop: {}};
var b = {prop: {}};

a.prop.circ = a.prop;
b.prop.circ = b;

console.log(deepDiff.diff(a, b));

Array order?

Based on the README

Changes to arrays are recorded simplistically. We care most about the shape of the structure; therefore we don't take the time to determine if an object moved from one slot in the array to another.

In other words, if a diff removes an object, and then we undo that diff, could the array order not be the same?

diff() does not detect properties added to functions

How to reproduce:

var original = {
  obj: {},
  func: function () {}
};
var modified = _.merge({}, original);
modified.obj.added = 'test';
modified.func.added = 'test';

var differences = DeepDiff.diff(original, modified);
console.log(JSON.stringify(differences));
// -> [{"kind":"N","path":["obj","added"],"rhs":"test"}]

Expected output:

[{"kind":"N","path":["obj","added"],"rhs":"test"},{"kind":"N","path":["func","added"],"rhs":"test"}]

The issue occurs in Chrome 48 (I didn't test other browsers or Node yet, but I doubt it makes a difference) with version 0.3.4 of the library, and version 4.11.1 of lodash. Both were downloaded from NPM.

I don't think it's an issue with _.merge(), since that is the best way I have found yet to copy an object, modify the copy, and find the changes using this library. It works great in all scenarios I'm currently working on, except for function properties.

When manually trying to reproduce this issue similar to what's described in Readme.md (by creating two identical objects that have an empty function each), the functions themselves are detected as an edit, regardless of the changed property.

@georgms is interested in this as well.

Bower "no tag found that was able to satisfy 0.3.3"

I don't know enough about Bower packaging, so I don't see the reason I am getting this. I have tried updating bower.json to "deep-diff": "0.3.3", and tried updating from 0.3.2. Any ideas?

bower update deep-diff
bower deep-diff#0.3.3       not-cached git://github.com/flitbit/diff.git#0.3.3
bower deep-diff#0.3.3          resolve git://github.com/flitbit/diff.git#0.3.3
bower deep-diff#0.3.3     ENORESTARGET No tag found that was able to satisfy 0.3.3

Additional error details:
Available versions in git://github.com/flitbit/diff.git: 0.3.2, 0.3.1, 0.3.0, 0.2.0, 0.1.7, 0.1.6, 0.1.4, 0.1.3, 0.1.2, 0.1.1

Can someone more knowledgeable about Bower fix this?

Thank you!

Ryan

A question about applying a diff.

Hi,

This is probably pretty simple, it just doesn't seem to be working as I expect. I have a Node app and am comparing an old record to a new one and calculating a diff. I am then sending that diff to the browser where an old version of the record resides. I am then attempting to apply the diff and having no luck.

So I tried to do it all in the browser and ran the following:
var arr1 = [1,2,3,4];
var arr2 = [1,2,3,4,5,6,7];
var diffs = DeepDiff(arr1, arr2);
DeepDiff(arr1, diffs);

Expecting to output the same as arr2? Instead I get an error.

Any suggestions.

Best regards,
Paul

Awesome

I don't have an issue, I just wanted to thank you for creating an awesome library. So so so helpful!

Error is thrown if a lhs property is an object and rhs is null

Here's an example that causes the error. It appears to be because typeof returns type 'object' for null values.

var Diff = require('deep-diff');


var lhs = {
    a: 'a',
    a1: [
        {
            b1: 'b1',
            b2: {c1: 'c1'},
            b3: 'b3'
        }
    ]
};

var rhs = {
    a: 'a',
    a1: [
        {
            b1: 'b1',
            b3: null,
            b2: null
        }
    ]
};

var diff = Diff(lhs, rhs);
console.log(diff);

Here's the error.

/Users/daniel/WorkProjects/esc/xpress-utils/historycleanup/node_modules/deep-diff/index.js:113
                var pkeys = Object.keys(rhs);
                                   ^
TypeError: Object.keys called on non-object
    at Function.keys (native)
    at deepDiff (/Users/daniel/WorkProjects/esc/xpress-utils/historycleanup/node_modules/deep-diff/index.js:113:26)
    at stack.length (/Users/daniel/WorkProjects/esc/xpress-utils/historycleanup/node_modules/deep-diff/index.js:117:9)
    at Array.forEach (native)
    at deepDiff (/Users/daniel/WorkProjects/esc/xpress-utils/historycleanup/node_modules/deep-diff/index.js:114:13)
    at deepDiff (/Users/daniel/WorkProjects/esc/xpress-utils/historycleanup/node_modules/deep-diff/index.js:105:9)
    at stack.length (/Users/daniel/WorkProjects/esc/xpress-utils/historycleanup/node_modules/deep-diff/index.js:117:9)
    at Array.forEach (native)
    at deepDiff (/Users/daniel/WorkProjects/esc/xpress-utils/historycleanup/node_modules/deep-diff/index.js:114:13)
    at accumulateDiff (/Users/daniel/WorkProjects/esc/xpress-utils/historycleanup/node_modules/deep-diff/index.js:136:4)

Source–dependent application of diffs, right?

So, this doesn't generate diffs that are standalone and could be applied to a target, independently of a source, right? Applying changes depends on the availability of the source, right?

Diff returns undefined

I have a piece of code where I want to compare two objects (these objects are retrieved from mongo with Mongoose) and I do:

var diff = require('deep-diff').diff;
var delta = diff(menu1, menu2); //menu1 and menu2 are objects retrieved from mongo

Unfortunately delta object is undefined.

Filter/Ignore Keys?

I just started using this library with AngularJS to track changes, and it works great so far!

The only short-coming is that Angular will sometimes add Angular-specific properties to objects (such as $$hashkey) for improving dirty-check speeds.

What are your thoughts on being able to supply a filter or array of properties to ignore?

I can submit a PR, but wanted feedback first :)

Thanks!

Bower "no tag found that was able to satisfy 0.3.3"

It looks like the tag 0.3.3 needs to be added in order for bower to install the newest version properly.

bower update deep-diff
bower deep-diff#0.3.3       not-cached git://github.com/flitbit/diff.git#0.3.3
bower deep-diff#0.3.3          resolve git://github.com/flitbit/diff.git#0.3.3
bower deep-diff#0.3.3     ENORESTARGET No tag found that was able to satisfy 0.3.3

Additional error details:
Available versions in git://github.com/flitbit/diff.git: 0.3.2, 0.3.1, 0.3.0, 0.2.0, 0.1.7, 0.1.6, 0.1.4, 0.1.3, 0.1.2, 0.1.1

In the meantime before this tag is added, you can use this to install 0.3.3.

bower i "[email protected]:flitbit/diff.git#619f6606ecef4098c4259db48387bebe68840ea" --save

Can a contributor add this tag? Thanks!

Ryan

FeatureRequest: change the diff of array elements (or add such an option)

For our auditing system we needed to persist the whole array element
and not just the difference.

The object difference for

const objA = {array: [{a: 1}]};
const objB = {array: [{a: 2}]};

would look in the original deep-diff like:

[{
  kind: "E",
  lhs: 1,
  rhs: 2,
  path: ["array", 0, "a"]
}]

Our need is that the result keeps the original and changed elements. It also has the kind as A and changes the structure a bit:

[{
   kind: "A",
   path: ["array", 0],
   item: {
       kind: "E",
       path: ["a"],
       elementLeft: {a: 1},
       elementRight: {a: 2},
       lhs: 1,
       rhs: 2
   }
}]

You could add an option to change the default behavior so that it creates diffs of edited array elements in the proposed manner. I've made a small project deepdiff-keep-element where you can check our intentions in tests.

Allow Custom Accessor and Mutator Functions

I was wondering what the consensus was of adding an interface to provide the ability to use custom getters and setters? Possibly as an argument to applyChange or revertChange. This would be extremely useful in MVC frameworks like EmberJS which insist on using the provided accessors.

Determine Shallow Change

I'm pretty sure this is possible currently but not sure the best approach.

Given an object like:

[
    {
        name: "Panda",
        types: ["red", "white"],
        food: "bamboo"
    },
    {
        name: "Monkey",
        types: ["brown", "white"],
        food: "bananas"
    }
]

If I change the first object twice but not the second object at all I would get a diff with 2 different changes for the first object ( great! ) but say I only care if the first object changed at all, now I have to filter out based on paths ( not a big deal for this but big lists would be annoying ).

Any thoughts on a better approach?

Please provide support for AngularJs apps

I tried using diff in one of my angular apps but it didn't work.

  1. I installed using the command "bower install deep-diff --save".
  2. I included the script in my index.html - "<script src="bower_components/deep-diff/releases/deep-diff-0.3.1.min.js"></script>"
  3. Last I injected it in my app as ['deep-diff']

Console gives an error - "Module 'deep-diff' is not available!"

Having trouble understanding how the prefilter should work

I am a little bit confused by the documentation of the pre-filter functionality.

At one point in the readme, it says:
"Diff arguments:
prefilter - an optional function that determines whether difference analysis should continue down the object graph."

And,
"Pre-filtering Object Properties
The prefilter's signature should be function(path, key) and it should return a truthy value for any path-key combination that should be filtered. If filtered, the difference analysis does no further analysis of on the identified object-property path."

But there is no actual instance of a diff that uses the pre-filter in the readme or examples that I could find. Something showing exactly how to use the following function would be great!

diff.diff(lhs, rhs, function (path, key) {
    //logic
    }
});

The only thing I could find was:

observableDiff(lhs, rhs, function (d) {
    // Apply all changes except those to the 'name' property...
    if (d.path.length !== 1 || d.path.join('.') !== 'name') {
        applyChange(lhs, rhs, d);
    }
});

Which isn't the diff.diff method for one, and doesn't take in two arguments for another.

Awesome package and thanks!

Crash with objects without toString method

I was getting the below crash.
This may not be frequent, but https://github.com/alunny/node-xcode produces objects that do not have .toString in their prototype.
I have a patch, I will create a PR.

$PROJECT/node_modules/deep-diff/index.js:134
    } else if (/^\/.*\//.test(subject.toString())) {
                                      ^
TypeError: undefined is not a function
    at realTypeOf ($PROJECT/node_modules/deep-diff/index.js:134:39)
    at deepDiff ($PROJECT/node_modules/deep-diff/index.js:157:16)
    at accumulateDiff ($PROJECT/node_modules/deep-diff/index.js:204:5)
    at Object.<anonymous> ($PROJECT/diff-xcode.js:19:19)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.runMain [as _onTimeout] (module.js:501:10)
    at Timer.listOnTimeout (timers.js:110:15)

No revertDiff functionality

First of all, awesome diffing library! I use it for undo/redo management of objects. However, I am missing a revertDiff function that does exactly the opposite of applyDiff:

b === applyDiff(a, diff(a, b))
a === revertDiff(b, diff(a, b))

The only way to add this functionality is to alter the library, since the deepDiff (not exposed to the outside) function needs to be called. Before I start fiddling in the module code, I was wondering if there was a good reason that this functionality is not there yet, and if there might be something that I am overlooking.

Invalid diff between two arrays?

When I do this:

var a1 = ["value"], a2 = ["other_value"];

diff = DeepDiff.diff(a1, a2);

I get diff[0].kind == 'E' with diff[0].path[0] == 0 instead of ..kind == 'A'. Is this intentional? If so, why?

question: diff.observableDiff length

hi

first thanks for this module, very nice :)

just a question

when i call observableDiff(old, new, function (d) {....

is it possible to know by advance how many kind N i have ? and does n have a length ?

thanks

Changes to dates aren't registered on the diffs

The typeof on a date is object so it falls through the object handling routine which looks for properties. Obviously, this could be true for a lot of different custom types; but Date might be common enough to support.

    describe('A target that has a date value', function() {
        var lhs = { key: new Date(555555555555) };

        it('shows the property is changed with a new date value', function() {
            var diff = deep.diff(lhs, { key: new Date(777777777777) });
            expect(diff).to.be.ok();
            expect(diff.length).to.be(1);
            expect(diff[0]).to.have.property('kind');
            expect(diff[0].kind).to.be('E');
        });

    });

Diff not working for some objects

var obj1 = {
  "level1.1": {
    "x": {
      "b": 1,
      "c": 1
    },
    "y": {
      "b": 1,
      "c": 1
    },
    "z": {
      "b": 2,
      "c": 2
    }
  },
  "level1.2": {
    "m": {
      "b": 1,
      "c": 1
    },
    "n": {
      "b": 1,
      "c": 1
    }
  }
}

var obj2 = {
  "level1.1": {
    "x": {
      "b": 1,
      "c": 1
    },
    "y": {
      "b": 1,
      "c": 1
    }
  },
  "level1.2": {
    "m": {
      "b": 1,
      "c": 1
    },
  }
}

var diff = require('object-deep-diff')
console.log(diff(obj1,obj2)) // logs {}

Is the second argument (source) of applyChange superfluous?

From the interface point of view the applyChange function should not require the source object used while taking the diff. Therefore I found it confusing when I was trying it. I found that passing the second argument as empty object did not change the behavior. So when I looked into the code, the source argument is indeed not being used anywhere (except the check).

https://github.com/flitbit/diff/blob/master/index.js#L248-L272

Do you plan to remove it in future? It's important to know this because in my use case I compute the diff, save it to persistent storage and in future apply it on an object to get the original object. i.e. I don't have the source object in that scenario.
Thanks.

Why does applyChange require the source parameter?

In my code I'm maintaining a list of changes, yet not maintaining the source object (as it was when the changes occurred).

Later, I want to apply the changes to a target, and conceptually see no reason why I'd need to have the source (the changes have all needed information).

Taking a look at applyChange's source, that parameter is seemingly not used.

My 'workaround' is simply just to pass the target again, but I see no reason why this parameter exists in the first place.

Deleting Array elements

Not sure but I think I've run into an issue dealing with deleting array elements. For example:

oldArray: [thing1, thing2, thing3, thing4]
newArray: [thing1, thing2]

I apply the diff using this code:

diff.observableDiff(oldArray, newArray, function (d) {
diff.applyChange(oldArray, newArray, d);
});

And I expect:

oldArray: [thing1, thing2]

But I get:

oldArray: [thing1, thing2, thing4]

Not sure why this is. Is this an issue with my code or yours. Any help is greatly appreciated. Thanks in advance.

Diffing array is very inefficient if deletion/addition occurs anywhere but at the end of the array

Often an array will have an element inserted or deleted from some index within the array. As it stands, deepDiff seems to treat such an event as an insertion or deletion of the final member of the array, and an edit of all the other members. Example:

When a "c" is inserted into the first array:
var a = [h, a, p, p, y]
var b = [c, h, a, p, p, y]

diff(a,b) will output a bunch of edited values for the array values 0-4 and say that the y has been inserted.

Ideally, for memory savings at least, we could use some sort of fuzzy alignment of the objects being held in the two arrays to find the best match-up of indices and then have a way of notating insertions and deletions.

Do you think this is a feature you could see building in the future? Would your diff system be amenable to something like this or would it break too many aspects of it?

Also note I would be interested in helping build any such system.

Thanks for you time!

Taking diff of two array's not working

Taking the diff like so:

var lhs = ["a","a"];
var rhs = ["a"];
var differences = deep.diff(lhs, rhs);
differences.forEach(function (change) {
        deep.applyChange(lhs, true, change);
});

fails when trying to apply that change with this message:

/Users/trich/Sites/deepDiff/index.js:195
, last = change.path.length - 1
^
TypeError: Cannot read property 'length' of undefined
at Function.applyChange (/Users/trich/Sites/deepDiff/index.js:195:27)
at observed (/Users/trich/Sites/deepDiff/examples/example1.js:38:14)
at Array.forEach (native)
at Object. (/Users/trich/Sites/deepDiff/examples/example1.js:37:13)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)

Bug in recursive `revertChange`

Hi -- thanks for the great package!

It seems there is an issue with applying revertChange in objects that have deep changes. Code snippet that illustrates the problem:

var dd     = require('deep-diff');

var before = {
    name: 'my object',
    description: 'it\'s an object!',
    details: {
        it: 'has',
        an: 'array',
        with: ['a', 'few', 'elements']
    }
};

var after = {
    name: 'updated object',
    description: 'it\'s an object!',
    details: {
        it: 'has',
        an: 'array',
        with: ['a', 'few', 'more', 'elements', { than: 'before' }]
    }
};

var revertDiff = function(src, d) {
    d.forEach(function (change) {
        dd.revertChange(src, true, change);
    });
    return src;
}

var clone = function(src) {
    return JSON.parse(JSON.stringify(src));
}

var df = dd.diff(before, after);
var b1 = clone(before);
var a1 = clone(after);

console.log(JSON.stringify(after));
console.log(JSON.stringify(revertDiff(after, df)));
console.log(JSON.stringify(b1 ));

This prints..

{"name":"updated object","description":"it's an object!","details":{"it":"has","an":"array","with":["a","few","more","elements",{"than":"before"}]}}
{"name":"my object","description":"it's an object!","details":{"it":"has","an":"array","with":["a","few","elements",{"than":"before"}]}}
{"name":"my object","description":"it's an object!","details":{"it":"has","an":"array","with":["a","few","elements"]}}

..instead of the correct (note the second line -- it should have been the b1 object):

{"name":"updated object","description":"it's an object!","details":{"it":"has","an":"array","with":["a","few","more","elements",{"than":"before"}]}}
{"name":"my object","description":"it's an object!","details":{"it":"has","an":"array","with":["a","few","elements"]}}
{"name":"my object","description":"it's an object!","details":{"it":"has","an":"array","with":["a","few","elements"]}}

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.