In my Node/MongoDB back-end I am doing some post-processing to generate notes when something changes in a record. So the first step is to get a pre
and post
update version of the record. Then I want to compare the two to identify the part of the record that changed. The solution I have below works - but it returns the root level property containing the change. I need something more granular than this - as I have an array -- "history", embedded within the root level element, also an array -- "services".
So, taking for example my two objects below, is there a way I can just pull out the the last element in the "history" array for obj2 -- since, in this case, that's what's changed, and that's what I need to key in on for then generating my note?
By the way, if there is an Underscore or Lodash way to handle this, I'm completely open to that as well.
Here's the code I have now:
const obj = {
_id: 1,
services: [
{
_id: 23,
service: "serviceOne",
history: [
{
_id: 33,
stage: "stageOne"
}
]
},
{
_id: 24,
service: "serviceTwo",
history: [
{
_id: 44,
stage: "stageOne"
}
]
},
]
};
const obj2 = {
_id: 1,
services: [
{
_id: 23,
service: "serviceOne",
history: [
{
_id: 33,
stage: "stageOne"
}
]
},
{
_id: 24,
service: "serviceTwo",
history: [
{
_id: 45,
stage: "stageTwo"
},
{
_id: 44,
stage: "stageOne"
}
]
},
]
};
let diff = Object.keys(obj).reduce((diff, key) => {
if (obj[key] === obj2[key]) return diff
return {
...diff,
[key]: obj2[key]
}
}, {})
console.log('diff: ', diff);