Last active
January 29, 2017 18:30
-
-
Save mattphillips/d6634fb745cae541288fe023e0c7e7a5 to your computer and use it in GitHub Desktop.
How to convert detailedDiff deleted undefined values into nulls :)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this is an example of what may be returned by the detailedDiff function | |
const detailedDifference = { | |
added: { | |
matt: 'phillips', | |
}, | |
updated: { | |
hello: 'world', | |
}, | |
deleted: { | |
a: { | |
b: { | |
c: undefined, | |
}, | |
d: undefined, | |
}, | |
e: undefined, | |
}, | |
}; | |
// this function is written in es6. if you are using es5 then just change `() => { }` to be `function () { }` | |
// it takes the deleted object and turns the undefined values into null (or another value just change the null on line 25) | |
const mapUndefinedToNull = (deleted) => { | |
return Object.keys(deleted).reduce((acc, key) => { | |
if (deleted[key] === undefined) { | |
return Object.assign({}, acc, { [key]: null }); | |
} | |
return Object.assign({}, acc, { [key]: mapUndefinedToNull(deleted[key]) }); | |
}, {}); | |
}; | |
const detailedDifferenceWithNulls = Object.assign({}, detailedDifference, { deleted: mapUndefinedToNull(detailedDifference.deleted) }); | |
console.log(JSON.stringify(detailedDifferenceWithNulls, null, 2)); // logs: | |
/* | |
{ | |
"add": { | |
"matt": "phillips" | |
}, | |
"updated": { | |
"hello": "world" | |
}, | |
"deleted": { | |
"a": { | |
"b": { | |
"c": null | |
}, | |
"d": null | |
}, | |
"e": null | |
} | |
} | |
*/ |
do i need to include something like
const difference = require('deep-object-diff').detailedDiff ;
??
@edwardsmarkf apologises I'd not refactored all the uses of difference
to detailedDifference
I've just updated the gist
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cut/paste result: (node 7.3)
const detailedDifferenceWithNulls = Object.assign({}, difference, { deleted: mapUndefinedToNull(difference.deleted) });
^
ReferenceError: difference is not defined
at Object. (/root/diff-testers/deep-object-diff/x.js:31:55)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3