mattphillips / deep-object-diff

Deep diffs two objects, including nested structures of arrays and objects, and returns the difference. ❄️
https://www.npmjs.com/package/deep-object-diff
MIT License
1.05k stars 89 forks source link

Deleted result is missing fields that were removed in target. #10

Closed JohnGrantPGA closed 7 years ago

JohnGrantPGA commented 7 years ago

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": {}
    }
}
mattphillips commented 7 years ago

Hey @JohnGrantPGA I suspect that the issue is because the difference between a and b is being converted into JSON with JSON.stringify.

undefined is not supported in JSON, so any key/ value pairing that is undefined will be filtered out when using JSON.stringify.

What you could do instead is supply a function to JSON.stringify(obj, fn) to convert any undefined values into something of your choosing :smile:.

Heres an example that converts undefined values to null:

function replacer(key, value) {
  if (value == undefined) {
    return null;
  }
  return value;
}

const a = [{
  "field1": "value1",
  "field2": "value2",
  "field3": "value3"
}];
const b = [{
  "field1": "value1",
  "field2": "value2"
}];

const difference = detailedDiff(a, b);

console.log(JSON.stringify(difference, replacer));
// {"added":{},"deleted":{"0":{"field3":null}},"updated":{}}
JohnGrantPGA commented 7 years ago

Hi Matt,

Thanks for the quick response! You're spot on. I incorporated your suggestions. Thank you. :)