在我的Node/MongoDB后端,我正在做一些后处理,以便在记录中发生变化时生成注释。因此,第一步是获取记录的pre
和post
更新版本。然后,我想要比较这两个文件,以确定记录中发生更改的部分。我下面的解决方案是有效的--但它返回包含更改的根级属性。我需要比这个更细粒度的东西--因为我有一个数组--“历史”,它嵌入到根级元素中,也是一个数组--“服务”。
那么,以我下面的两个对象为例,有没有一种方法可以只提取obj2的“历史”数组中的最后一个元素--因为,在本例中,这就是更改的内容,我需要键入这些内容才能生成笔记?
顺便说一句,如果有下划线或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);
发布于 2019-02-06 14:11:41
你可以使用解构赋值
let {services:[,{history:[...data]}]} = obj2;
console.log(data.pop());
https://stackoverflow.com/questions/54555427
复制相似问题