问题描述
我已经做了一些工作来对两个对象(实际上是同一文档的保存前和保存后版本)之间(通过Underscore和 )进行深入比较,以便隔离保存后不同的部分。 以以下文档结构为例:
{
_id: 4d39fe8b23dac43194a7f571,
name: {
first: "Jane",
last: "Smith"
}
services: [
{
service: "typeOne",
history: [
{ _id: 121,
completed: true,
title: "rookie"
},
{ _id: 122,
completed: false,
title: "novice"
}
]
},
{
service: "typeTwo",
history: [
{ _id: 135,
completed: true,
title: "rookie"
},
{ _id: 136,
completed: false,
title: "novice"
}
]
}
]
}
如果将一个新元素添加到history
数组中,我就能成功解析出该更改。
但是,除了退出此已更改的部分外,我还希望能够有效地从history
中走出来,以找到service
的价值,因为我还需要知道两个services
数组元素中的哪一个实际发生了更改。
有什么办法可以使用本机es6 JavaScript做到这一点?
如果没有,是否可以使用库来确定? 现在,我可以通过索引获得“服务”的价值:
if (diff.path[1] === 0) {
targetService = "typeOne";
} else if (diff.path[1] === 1) {
targetService = "typeTwo";
} else if (diff.path[1] === 2) {
targetService = "typeThree";
}
但是从我的理解来看,这还不是完全的证明,因为不能保证“服务”中元素的顺序在某个时候不会改变。
我想如果可以在services
数组中强制元素的排序,则此索引方法可以工作。
我只是不确定是否有办法做到这一点(如果可能,可以征询建议)。
1楼
deep-diff
为您提供了实现此更改的途径,如下所示:
{
kind: 'N',
path: ['services', 1, 'history'],
// ... other properties
}
您可以使用以下路径来跟踪更改的对象:
tree.services[changes.path[1]].service // 'typeTwo'