Coder Social home page Coder Social logo

mattphillips / deep-object-diff Goto Github PK

View Code? Open in Web Editor NEW
1.0K 11.0 88.0 182 KB

Deep diffs two objects, including nested structures of arrays and objects, and returns the difference. ❄️

Home Page: https://www.npmjs.com/package/deep-object-diff

License: MIT License

JavaScript 100.00%
deep diff nested-structures object array

deep-object-diff's Introduction

Hey there 👋, I'm Matt Phillips.

Twitter Sponsor Blog


I'm a software engineer who is passionate about open-source software, functional programming, and testing. I'm a perpetual learner who loves sharing my knowledge on all things code, career development and building products.

If I'm not tinkering on my own products, I'm working on open-source. I've published multiple successful packages, which are downloaded millions of times each month, and most notably helped maintain Jest and the Jest Community.

I also share my experiences over on my blog. You can expect to learn more about Typescript, Node, React, Testing, and Functional Programming – with some content on career development and founding products thrown in too.

Twitter is the best place to keep up to date with what I'm working on, so follow along there for:

  • 👨‍💻 Web dev, functional programming & testing in Typescript
  • 🤩 Getting into / maintaining open source software
  • 💸 Tech entrepreneurship
  • 📢 Building in public
  • 🧑‍🚀 Career advice

Or wanna chat? My DMs are always open 😊.

If you want to help support my work then please consider sponsoring me on GitHub.

What I work on

Package Description Role Downloads
Jest Delightful JavaScript Testing. Maintainer jest downloads
jest-each Data driven testing for Jest. Author jest-each downloads
deep-object-diff Deep diff two JavaScript Objects. Author deep-object-diff downloads
jest-extended Additional Jest matchers 🃏💪 Author jest-extended downloads
jest-expect-message Add custom message to Jest expects. Author jest-expect-message downloads
jest-chain Chain Jest matchers together to create one powerful assertion. Author jest-chain downloads

deep-object-diff's People

Contributors

anko avatar beeequeue avatar greenkeeper[bot] avatar icholy avatar kamalaman avatar mattphillips avatar nitive avatar pixelblend avatar sheneekaw 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

deep-object-diff's Issues

detailedDiff doesn't return deleted elements

Deleted doesn't seem to work in the detailedDiff method. Examples:

let b1 = { a: 1 }
let b2 = {  }
console.log(JSON.stringify(differ.detailedDiff(b1, b2))); //output: {"added":{},"deleted":{},"updated":{}}
let b1 = { a: 1 }
let b2 = { b: 3 }
console.log(JSON.stringify(differ.detailedDiff(b1, b2))); //output: {"added":{"b":3},"deleted":{},"updated":{}}

Return type for `detailedDiff`

Update return type of detailedDiff to reflect the static top level properties:

Current:

export function detailedDiff (originalObj: object, updatedObj: object): object

Proposed:

type DetailedDiff = {
  added: object;
  deleted: object;
  updated: object;
};

export function detailedDiff (originalObj: object, updatedObj: object): DetailedDiff

Undefined value

should that be undefined?

Original: [ { _id: 123, id_content: 111, id_category: 22 } ]
New: [ { id_content: 111, id_category: 22 } ]
detailedDiff/diff: { added: {}, deleted: { '0': { _id: undefined } }, updated: {} }

[Feature request] Add filter

In order to compare objects, I want to filter some keys. For example:

lhs = {
"name": "a",
"phone": "b"
}

rhs = {
"name": "a",
"phone": "c"
}

diff(lhs, rhs, function filter(node){
   return node.name === 'phone'
})

Using for arrays? deleted seems to be wrong

Tried using it for arrays, but it seems deleted items are tackled incorrectly. The script is not taking the shortest path.

eg https://runkit.com/giorgio79/5bead0643e02a00012ed51d0

const { diff, addedDiff, deletedDiff, detailedDiff, updatedDiff } = require("deep-object-diff");

const wrong = [
 "Tom",
 ",",
 "was",
 "involved",
 "in"
];

const right = [
 "Tom",
 "was",
 "involved",
 "in"
 ];

console.log(detailedDiff(wrong, right));

getting

Object
added: Object {}
deleted: Object {4: undefined}
updated: Object {1: "was", 2: "involved", 3: "in"}

I would have expected
Object
added: Object {}
deleted: Object {1: ","}
updated: Object {}

Uncaught TypeError: (0 , _deepObjectDiff2.default) is not a function

Updated to 1.0.0 from previous version and get following on browser:

Uncaught TypeError: (0 , _deepObjectDiff2.default) is not a function at detectChangedData (http://localhost:8080/files/js/bundle.js:97295:44)

Code goes simply like this:

import diff from 'deep-object-diff';

const detectChangedData = ({ initialValues, currentValues }) => {
  const base = diff(initialValues, currentValues);
  return base;
};

React/redux project packed with Webpack 1.14.0, running node 7.4.0 and npm 4.0.5..

Wrong diff changing an undefined attribute to empty object

When you check against removed or undefined attributes it works fine:
✔️ diff({a:{}}, {a:undefined}) returns {a: undefined}
✔️ diff({a:{}}, {}) returns {a: undefined}

But when you invert and add/change to an empty object it differs depending if it was undefined or nonexistent before:
✔️ diff({}, {a:{}}) returns {a:{}}
diff({a:undefined}, {a:{}}) returns {} instead of {a:{}}

The array detailedDiff does not work

I am just trying this library for simple arrays and it's not working as I expected. This is the code:

const a1 = [2, 5, 8, 20];
const a2 = [5, 7, 9, 20];
const diff = detailedDiff(a1, a2);
// this is the result
// { added: {},
//   deleted: {},
//  updated: {0: 5, 1: 7, 2: 9} }

// I was expecting this result
// { added: {0: 7, 1: 9}
// deleted: {0: 2, 1: 8}
// updated: {}}

Can someone explain this result?

is there any apply method ?

Hi,

I was not able to find any apply method which would allow us to take a diff, and apply it to an object.
Is there one somewhere? Maybe in another repo?

As a user, I want to be able to compute a diff, send it to a remote host, and apply it (reverse it?), to compute the whole object.
Or should I rather use libraries based on jsonpatch ?

Does not detect differences in order

When diffing two objects where I would like the order of keys to matter:


const { diff, addedDiff, deletedDiff, detailedDiff, updatedDiff } = require("deep-object-diff");

const right = {
1: "Tom",
2: "reads",
3: ",",
4: "novels"
};

const wrong = {
1: "Tom",
2: "reads",
3: "novels",
4: ","
};

console.log(detailedDiff(right, wrong)); 

And the result is:

Object {added: , deleted: , updated: }

Basic diffing broken

Description
Basic diff functionality seems to be broken.

const detailedDiff = require("deep-object-diff").detailedDiff;

const lhs = {
  'a': 1,
  'b': 2
};

const rhs = {
  'a': 1
};

diff = detailedDiff(lhs, rhs);
console.log(JSON.stringify(diff, null, 2));
// Expected
{
  "added": {},
  "deleted": {
    "b": 2
  },
  "updated": {}
}
// Actual
{
  "added": {},
  "deleted": {},
  "updated": {}
}

https://repl.it/repls/ThankfulFumblingOpenlook

No version specified in mjs and cjs spawns errors in webpack

Hey, I have the following error with the latest version 1.1.7 saying that there is no version specified in package.json and there is no version in mjs/package.json

WARNING in shared module deep-object-diff -> /node_modules/deep-object-diff/mjs/index.js
No version specified and unable to automatically determine one. No version in description file (usually package.json). Add version to description file, or manually specify version in shared config.

Array diffs entirely on order and not contents

When I diff ['a', 'b', 'c'] and ['b', 'c'], the result is:

{
  added: {},
  deleted: { '2': undefined },
  updated: { '0': 'b', '1': 'c' }
}

I would expect the result to be:

{
  added: {},
  deleted: { '0': undefined },
  updated: { '0': 'b', '1': 'c' }
}

More specific type for detailedDiff()?

Would something like this make sense? If so I can submit a PR.

export type DetailedDiffResult = {
  deleted: object;
  added: object;
  updated: object;
};

export function detailedDiff(
  originalObj: object,
  updatedObj: object
): DetailedDiffResult;

Comparing objects with empty prototypes (no hasOwnProperty method)

I'm using deep-object-diff to compare objects generated by query-string. Structures returned by its parser have no hasOwnProperty method (sindresorhus/query-string#47) and so deep-object-diff can't work on them as it relies on the method.

Steps to reproduce:

var deepObjectDiff = require('deep-object-diff');

var a = Object.create(null);
a.foo = 'bar;

var b = Object.create(null);
b.foo = 'baz';

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

Error message:

TypeError: rhs.hasOwnProperty is not a function
    at C:\Users\nd\object-diff\node_modules\deep-object-diff\dist\diff\index.js:55:18

Problem with dates comparison

Once an object has dates, they seem to not compare, just get ignored.

  const oldItem = { someDate: new Date() };
  console.log('oldItem', oldItem);
  
  const newItem = { someDate: moment('2017-01-01').toDate() };
  console.log('newItem', newItem);

  const diffDetails = detailedDiff(oldItem, newItem);
  console.log('diffDetails', diffDetails);

outputs to:

oldItem { someDate: Tue Feb 14 2017 13:22:36 GMT+0100 (CET) }
newItem { someDate: Sun Jan 01 2017 00:00:00 GMT+0100 (CET) }
diffDetails { added: {}, deleted: {}, updated: {} }

Updated __proto__

I casting an object and I got an updated __proto__

const customerDiff: any = detailedDiff(this.customer, this.form.value as Customer);
{
  __proto__:Object {...}
}

Can I ignore it?

Use ECMAScript modules instead of CommonJS modules

Hi, building an Angular project with the latest version 10.0.7 I got this warning message
WARNING in C:[...]\filename.ts depends on 'deep-object-diff'. CommonJS or AMD dependencies can cause optimization bailouts.
For more info see: https://angular.io/guide/build#configuring-commonjs-dependencies

Is there any chance this library to be convert to ECMAScript modules? This will allow for a greater bundle size optimization at build time for apps that uses webpack or similar minifiers (https://web.dev/commonjs-larger-bundles/).

Thanks

Array Comparison

Hey,

If you diff two arrays that have some values, but are in a different order, i.e: [1, 3, 2], and [1, 2, 3] the result will be something like: updated position 2 and 3 instead of no change. Is this expected behavior? If so, is there any way I can implement the array to either be sorted or use something like Array.includes()?

extend logic for updatedDiff

For now .updatedDiff() method returns summary of updated keys with actual values.
All seems correct, but..
We already have new fresh object received with all actual data inside. Imagine we would like to save it and overwrite an old data. And wand to preserve changes history. No chance to get previous data for updated keys for now.

Maybe .updatedDiff(oldObj, newObj, [showOldValuesForUpdatedKeys= true|false ] )?

Cannot resolve module `deep-object-diff`

After installing I get the error Cannot resolve module 'deep-object-diff'.

I installed and implemented it the way you provided:

npm i --save deep-object-diff
import { updatedDiff } from 'deep-object-diff';

Comparing object with "hasOwnProperty" keys fails

I'm trying to use deep-object-diff to compare different copies of https://github.com/mdn/browser-compat-data, which is a dataset describing the web platform itself. As such, it has a key called "hasOwnProperty" to describe that method. deep-object-diff uses code like obj.hasOwnProperty(key) a lot, and obj.hasOwnProperty will in this case be an object in the BCD data, not Object.prototype.hasOwnProperty.

This causes deep-object-diff to throw an exception, the first place being here.

return r.hasOwnProperty(key) ? acc : { ...acc, [key]: undefined };

Simplified a bit, here's a subset of the data:

{
  "javascript": {
    "builtins": {
      "Object": {
        "hasOwnProperty": {
          "__compat": "an object with more stuff here"
        }
      }
    }
  }
}

Repro script showing the problem:

const { diff } = require("deep-object-diff");
diff({"hasOwnProperty": 1}, {"hasOwnProperty": 2});

This will throw "Uncaught TypeError: r.hasOwnProperty is not a function".

A possible fix for this would be to add a hasOwnProperty wrapper to https://github.com/mattphillips/deep-object-diff/blob/master/src/utils/index.js and always use that, but there may be other ways.

Type accounting rigour

When I compare two arrays:
1st arg = ['a', 'b', 'c']
and
2nd arg = ['a', 'b']

results in object:
{ '2': undefined }

I would expect -- given your immense abilities for designing software :P -- to get this:
[null/same?, null/same?, undefined]

if I have this problem:
1st argument: unchanged
2nd arg = ['a', 'c']

result would be:
[null/same?, 'c', undefined]

We don't need to prematurely quibble about perf do we lads?

What about rhs and lhs have an array and an obj?
1st arg = ['a', 'b', 'c']
2nd arg = {'1': "a", 'b': "c"}

I would output this result annotated with metadata:
{
type: Object,
value: 2nd arg = {'1': "a", 'b': "c"}
}
I realize this might be a tad too intrusive, maybe think of some prototype property(maybe through a proxy?) that could annotate the object without the interference to the output value ;)

Typescript custom type comparison support would be extra fancy ca$h that would make me want to SCREAM WITH JOY.

Love always ❤️,
Adrian

detailedDiff behavior when deleting items from an array does not match README.md documentation

According to the detailedDiff example in the README.md, the behavior of detailedDiff when deleting items from an array is to show the deleted items by index. I checked [email protected] (the version that the README.md was updated with detailedDiff and example usage) and the current version [email protected]. Instead of indicating the deleted object index within the array in the deleted section, it merely shows the array name in the deleted section with an empty object {}.

const { detailedDiff } = require('deep-object-diff');

const lhs = {
  foo: {
    bar: {
      a: ['a', 'b'],
      b: 2,
      c: ['x', 'y'],
      e: 100 // deleted
    }
  },
  buzz: 'world'
};

const rhs = {
  foo: {
    bar: {
      a: ['a'], // index 1 ('b')  deleted
      b: 2, // unchanged
      c: ['x', 'y', 'z'], // 'z' added
      d: 'Hello, world!' // added
    }
  },
  buzz: 'fizz' // updated
};

const objectDifferences = detailedDiff(lhs, rhs);
console.log(JSON.stringify(objectDifferences, null, 2));

/*  Results documented in README.md. Note that the array 'a' shows '1': undefined, indicating the item missing from the array by its index.
{
  added: {
    foo: {
      bar: {
        c: {
          '2': 'z'
        },
        d: 'Hello, world!'
      }
    }
  },
  deleted: {
    foo: {
      bar: {
        a: {
          '1': undefined
        },
        e: undefined
      }
    }
  },
  updated: {
    buzz: 'fizz'
  }
}
 */

/*
 * Results in [email protected]
{
  "added": {
    "foo": {
      "bar": {
        "c": {
          "2": "z"
        },
        "d": "Hello, world!"
      }
    }
  },
  "deleted": {
    "foo": {
      "bar": {
        "a": {}
      }
    }
  },
  "updated": {
    "buzz": "fizz"
  }
}
 */

/*
 * Results in current version [email protected]  (same as [email protected])
{
  "added": {
    "foo": {
      "bar": {
        "c": {
          "2": "z"
        },
        "d": "Hello, world!"
      }
    }
  },
  "deleted": {
    "foo": {
      "bar": {
        "a": {}
      }
    }
  },
  "updated": {
    "buzz": "fizz"
  }
}
 */

Usage of reduce spread

There could be noticeable perf improvements if we were to stop using the reduce spread pattern in the diffing methods.

Some benchmarks from changing the diff method to use basic for loops:

original x 377,694 ops/sec ±0.62% (86 runs sampled)
new x 788,699 ops/sec ±0.55% (91 runs sampled)

Reference: https://www.richsnapp.com/blog/2019/06-09-reduce-spread-anti-pattern

I have most of the work done in a fork. Would you be open to a PR?

Fix the bundle

Unfortunately I am forced to use the dist bundle to include the feature into my application (with a good old script tag).

I found that you populate the lib methods in a global index object.
However, this is not only a not very intuitive name. The actual problem is, that the object is filled with values of undefined.

index: {
__esModule: true,
addedDiff: undefined,
deletedDiff: undefined,
detailedDiff: undefined,
diff: undefined,
updatedDiff: undefined
}

Please fix that since it stops me from using this package at all :/

PS: I know about the horror of maintaining old packages. However, since you seem to bundle the package with babel only, I can't really help with a quick PR. It would be cool though if you would find some spare time to work on this

Arrays are returned as Objects,

I tried this library to do some diffs between two typescript objects and the problem that I faced in was that when the difference was returned all the arrays that i had in the object were converted to objects with keys the index of the element in the array

Comparing large arrays can take forever

To reproduce:

`const deepObjectDiff = require("deep-object-diff");

let a = new Array(10000);

for(let i=0; i<a.length; ++i){
a[i] = {
"attribute 1": i,
"attribute 2": i,
"attribute 3": i
};
}

let b = JSON.parse(JSON.stringify(a));
b.unshift({
"a": 9999999
});

let start = new Date().getTime();

let diff = deepObjectDiff.detailedDiff(a,b);

let end = new Date().getTime();
console.log("Took " + (end - start) + " milliseconds.")`

For an array of size 10000, it can take 40+ seconds.
20000 = about 250 seconds
25000 = about 500 seconds
If the array is very large, 100000+ , it can take a really long time.

detailedDiff returning confusing data

i look at the results of the diff and see

{added:{}, deleted:{}, updated:{}}

I compare against an object like that, and get not equal.

I json.stringify() the object and it looks the same
I check the number of keys in each section and see some number of keys in one of more areas (usually deleted)
but those keys are not in the object being compared.

BUT
I compare this object (old)

{
		compliments: {
			anytime: ["Hey there sexy!"],
			morning: ["Good morning, handsome!", "Enjoy your day!", "How was your sleep?"],
			afternoon: ["Hello, beauty!", "You look sexy!", "Looking good today!"],
			evening: ["Wow, you look hot!", "You look nice!", "Hi, sexy!"],
			"....-01-01": ["Happy new year!"]
		},
		updateInterval: 30000,
		remoteFile: null,
		fadeSpeed: 4000,
		morningStartTime: 3,
		morningEndTime: 12,
		afternoonStartTime: 12,
		afternoonEndTime: 17,
		random: true,
		mockDate: null
	}

against this (new)

compliments: {
            anytime: [
              "Hey there sexy!"
            ],
            morning: [
              "Good morning, handsome!",
              "Enjoy your day!",
              "How was your sleep?"
            ],
            afternoon: [
              "Hello, beauty!",
              "You look sexy!",
              "Looking good today!"
            ],
            evening: [
              "Wow, you look hot!",
              "You look nice!",
              "Hi, sexy!"
            ],
            "-01-01": [
              "Happy new year!"
            ]
          },
          updateInterval: 30000,
          fadeSpeed: 4000,
          morningStartTime: 3,
          morningEndTime: 12,
          afternoonStartTime: 12,
          afternoonEndTime: 17,
          random: true
        }

and get this

{
  "added": {
    "compliments": {
      "-01-01": [
        "Happy new year!"
      ]
    }
  },
  "deleted": {
    "compliments": {}
  },
  "updated": {}

but deleted is incomplete
"....-01-01" is not there

note this text is presented by JSON.stringify() on the objects..

Diffs on array entities return reference to original array

Here's an example:

var deepObjectDiff = require("deep-object-diff")

var orig = {}

var updated = {
    four: ['hello', 'byebye']
};

var diff = deepObjectDiff.diff(orig, updated);

delete diff.four[0];

console.log(diff, updated);

What I expect to see is that after deleting the key from the 'diff', my 'updated' variable should remain unchanged. However, because 'diff' is returning a reference to the array that got updated, when I delete the an array entry from 'diff', it mutates 'updated'.

Any chance we can get this fixed?

Thanks!

Arrays are being transformed into objects

When running deep-object-diff on an object which contains arrays those arrays are turned into objects.

Object on which deep-object-diff is used:

{
    "Order": [{
        "OrderLines": [{
            "canEditQty": true,
            "ProductId": "1234",
            "ProductCode": "sku-1234",
            "QtyAvailable": "5",
            "QtyOrdered": "5",
            "QtyInvoiced": "0",
            "QtyShipped": "5",
            "QtyInitialBo": "0",
            "QtyBo": "0",
            "Total": 6.8,
            "Price": 1.36,
            "PriceText": "$1.36",
            "PriceMatchStatus": 0,
            "OriginalPrice": 1.36,
            "OriginalPriceText": "$1.36",
            "IsPriceMatch": false
        }]
    }]
}

Those values are changed to :
QtyOrdered: "7"
Total: "9.52"
Price: "1.36"

Result of deep-object-diff:

{
    "Order": {
        "0": {
            "OrderLines": {
                "0": {
                    "QtyOrdered": "7",
                    "Total": "9.52",
                    "Price": "1.36"
                }
            }
        }
    }
}

This creates issues where we expect some data to be arrays and they are now objects.

detailedDiff behavior when the last item in an array is deleted, breaking change between 1.1.0 and 1.1.7

The behavior of a detailedDiff result changed from [email protected] and [email protected]. Based on my interpretation of the README.md example for detailedDiff, neither 1.1.0 nor 1.17 behavior matches the documentation ( See issue #74 ).
In version 1.1.0, if the last item in the array is deleted, then the change is indicated in the deleted section of the diff results.
In the current version, 1.1.7, if the last item in the array is deleted, then the change is indicated in both the deleted section and the updated section of the diff results.

const { detailedDiff } = require('deep-object-diff');

const lhs = {
  someArray: [ 'a'
  ]
};

const rhs = {
  someArray: [
  ]
};

const objectDifferences = detailedDiff(lhs, rhs);
console.log(JSON.stringify(objectDifferences, null, 2));

/*
 * Results in [email protected]
{
  "added": {},
  "deleted": {
    "someArray": {}
  },
  "updated": {}
}
 */

/*
 * Results in current version [email protected]
{
  "added": {},
  "deleted": {
    "someArray": {}
  },
  "updated": {
    "someArray": {}
  }
}
 */

/*
 * Expected results based on my interpretation of https://github.com/mattphillips/deep-object-diff#detaileddiff
{
  "added": {},
  "deleted": {
    "someArray": {
      '0': undefined
    }
  }
}
 */

Keep arrays as arrays

Hi guys! First of all, great work on this project!

I was thinking if you find it useful to keep arrays as arrays on the resulting diff object, something like:

      let difference = diff(l[key], r[key])
      if (Array.isArray(l[key])) {
        difference = Object.entries(difference).map(d => d[1])
      }

If it's interesting to you I can submit a PR to do that!

String/number comparison

The tool returns a diff whenever a comparison is done between string value and number.

Example: "8" and 8 is returned as different.

delete return value

could we include this gist with deep-object-diff and use a parameter with detailedDifference( function?

something like:

detailedDifference(lhs, rhs, null);   // return null rather than undefined
detailedDifference(lhs, rhs, '{}' ) ;   // return {} rather than undefined

Proposal: Add an 'areSame' flag.

basically, each diff type can have an additional flag, areSame, which is set true if the objects are the same.

This functionality can be achieved with this:

const result = detailedDiff(oldItem, newItem); 
const areSame = Object.values(result).reduce((acc, cur) => {
        return acc && Object.values(cur).length === 0
    }, true); 

Nested empty object with no change counts as a change

If I pass the same object, which nests another object with no properties as a child, as both arguments of diff or detailedDiff, it will show that the change occurred and the change is an empty object.

const obj = { subObj: {} }
const difference = diff(obj, obj)
console.log(difference) // { subObj: {} }

In my application I needed to do this to circumvent the issue:

const difference = detailedDiff(objectBefore, objectAfter)
let changeOccured = Object.keys(difference).length > 0
if (changeOccured) {
    for (let change in difference) {
        if (typeof difference[change] == 'object' && Object.keys(difference[change]).length == 0) {
            changeOccured = false
        } else changeOccured = true
    }
 }

P.S. With detailedDiff this kind of 'change' is counted as "added".

an option to detect "inserted" and removed items in arrays

diff(['a', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e'])

the current behavior is to treat indexes 1, 2 and 3 as changed and 4 as added

{ '1': 'b', '2': 'c', '3': 'd', '4': 'e' }

it would be nice if it was able to detect that only one value was added. something like this:

{ inserts: { 1: 'b' } }

Also return original values for deleted and updated? Feature request.

Hi Matt. Great package thanks.

Would you be able to create versions of deletedDiff, updatedDiff, detailedDiff or have them accept an optional shouldShowOriginal argument to also return the original values too? Eg:

const lhs = {
  foo: {
    bar: {
      a: ['a', 'b'],
      b: 2,
      c: ['x', 'y'],
      e: 100 // deleted
    }
  },
  buzz: 'world'
};

const rhs = {
  foo: {
    bar: {
      a: ['a'], // index 1 ('b')  deleted
      b: 2, // unchanged
      c: ['x', 'y', 'z'], // 'z' added
      d: 'Hello, world!' // added
    }
  },
  buzz: 'fizz' // updated
};

console.log(detailedDiff(lhs, rhs, true));

/*
{
  added: {
    foo: {
      bar: {
        c: {
          '2': 'z'
        },
        d: 'Hello, world!'
      }
    }
  },
  deleted: {
    foo: {
      bar: {
        a: {
          '1': undefined
        },
        e: undefined
      }
    }
  },
  deletedOriginal: {
    foo: {
      bar: {
        a: ['a', 'b'],
        e: 100
      }
    }
  },
  updated: {
    buzz: 'fizz'
  }
  updatedOriginal: {
    buzz: 'world'
  }
}
*/

Obviously just showing detailedDiff implementation but would be same for deletedDiff, updatedDiff.

Thanks.
Sean

Deleted result is missing fields that were removed in target.

These are my source and target objects and my result of a detailed diff. Shouldn't the deleted property contain, field3?

$ node app.js
{
    "a": [
        {
            "field1": "value1",
            "field2": "value2",
            "field3": "value3"
        }
    ],
    "b": [
        {
            "field1": "value1",
            "field2": "value2"
        }
    ],
    "result": {
        "added": {},
        "deleted": {
            "0": {}
        },
        "updated": {}
    }
}

deep-object-merge ?

const originalObject = {...}
const newObject = {...}
const diffObject = deep-object-diff.diff(originalObject, newObject)

Is there a suggested solution how to get new object merging original object with diff object created with deep-object-diff?


I intend to store original object + diff, so later I can merge those two to get new object. Then I compare original with new object using some other lib and render diff on a page.

Better support for dates

When you check if two dates are equal to each other you run the following code:

if ((0, _utils.isDate)(l) || (0, _utils.isDate)(r)) {
   if (l.toString() == r.toString()) return {};
   return r;
}

The issue here is that new Date(1).toString() === new Date(2).toString() //true which is obviously false.

The issue here is that toString formats the date object into a human readable format which does not take milliseconds into account Mon Sep 28 1998 14:36:22 GMT-0700 (PDT)

What you should be using instead is .valueOf() which converts the date into an epoch time. This is also much more preferment than toStirng: roughly 25x faster in node 7.

updatedDiff() not suitable for nested array?

Having this original object:

originalResource = {
  id: null,
  name: null,
  tags: [],
  coordinates: null,
  transforms: null
}

And the one with the updated property tags


resource = {
  id: null,
  name: null,
  tags: ['lorem', 'ipsum'],
  coordinates: null,
  transforms: null
}

The result of doing

updatedDiff(originalResource.value, resource.value)
// {}

Am I missing something? I just wanted to use only updatedDiff() method to make things easier.
Any advice will be appreciated

BTW, it would be interesting to have a method just for listing all properties that have been touched. I'm aware about detailedDiff(), but in a plain way with no details could be useful for knowing what properties are "dirty"

pass thru of arrays

Hi

Thank you for a nice diff library. Our need is simply to get the new/updated array passed back as the diff. Having options to diff(.., {returnArray:true}) would be nice.

The code:
in diff/index.js justafter line 55
if (Array.isArray(r)) {
return r;
}

Regards
Michael

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.