Comparing Objects and Pulling Out Deep Diff

点点圈 提交于 2020-01-06 08:35:06

问题


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);

回答1:


You can use destructuring assignment

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

console.log(data.pop());


来源:https://stackoverflow.com/questions/54555427/comparing-objects-and-pulling-out-deep-diff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!