在Node / MongoDB后端中,我正在做一些后期处理,以在记录中发生某些更改时生成注释。因此,第一步是获取记录的pre
和post
更新版本。然后,我想将两者进行比较,以识别更改的记录部分。我下面的解决方案有效-但它返回包含更改的根级别属性。我需要比这更精细的东西-因为我有一个数组-“历史”,嵌入在根级别元素中,还有一个数组-“服务”。
因此,以下面的两个对象为例,有一种方法可以将obj2的“ history”数组中的最后一个元素拉出来-因为在这种情况下,这就是更改的内容,所以我需要输入才能生成我的笔记?
顺便说一句,如果有Underscore或Lodash处理方式,我也完全可以接受。
这是我现在拥有的代码:
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);
答案 0 :(得分:2)
您可以使用解构分配
let {services:[,{history:[...data]}]} = obj2;
console.log(data.pop());