0

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);
Muirik
  • 6,049
  • 7
  • 58
  • 116
  • 1
    Possible duplicate of [Generic deep diff between two objects](https://stackoverflow.com/questions/8572826/generic-deep-diff-between-two-objects) – Heretic Monkey Feb 06 '19 at 14:18

1 Answers1

2

You can use destructuring assignment

let {services:[,{history:[...data]}]} = obj2;

console.log(data.pop());
guest271314
  • 1
  • 15
  • 104
  • 177
  • @Muirik The array assigned to the `history` property. If there will be only a maximum of 2 elements you can use `let {services:[,{history:[, data]}]} = obj2;` – guest271314 Feb 06 '19 at 14:18
  • Okay, got it, thanks! In my case there could be many elements within the "history" array, so I will stick with your posted example. – Muirik Feb 06 '19 at 14:22