I have two objects: oldObj
and newObj
.
(我有两个对象: oldObj
和newObj
。)
The data in oldObj
was used to populate a form and newObj
is the result of the user changing data in this form and submitting it.
(oldObj
中的数据用于填充表单,而newObj
是用户更改此表单中的数据并提交后的结果。)
Both objects are deep, ie.
(两个物体都很深,即。)
they have properties that are objects or arrays of objects etc - they can be n levels deep, thus the diff algorithm needs to be recursive.(它们具有对象或对象数组等属性-它们的深度可以为n级,因此diff算法需要递归。)
Now I need to not just figure out what was changed (as in added/updated/deleted) from oldObj
to newObj
, but also how to best represent it.
(现在,我不仅需要弄清楚从oldObj
到newObj
更改(如添加/更新/删除),还需要如何最好地表示它。)
So far my thoughts was to just build a genericDeepDiffBetweenObjects
method that would return an object on the form {add:{...},upd:{...},del:{...}}
but then I thought: somebody else must have needed this before.
(到目前为止,我的想法只是建立一个genericDeepDiffBetweenObjects
方法,该方法将以{add:{...},upd:{...},del:{...}}
的形式返回对象,但后来我想到:有人否则一定需要这个。)
So... does anyone know of a library or a piece of code that will do this and maybe have an even better way of representing the difference (in a way that is still JSON serializable)?
(那么...是否有人知道可以做到这一点的库或一段代码,也许有一种更好的方式来表示差异(以仍可序列化JSON的方式)?)
Update:(更新:)
I have thought of a better way to represent the updated data, by using the same object structure as newObj
, but turning all property values into objects on the form:
(我想过一种更好的方式来表示更新的数据,方法是使用与newObj
相同的对象结构,但将所有属性值都转换为表单上的对象:)
{type: '<update|create|delete>', data: <propertyValue>}
So if newObj.prop1 = 'new value'
and oldObj.prop1 = 'old value'
it would set returnObj.prop1 = {type: 'update', data: 'new value'}
(因此,如果newObj.prop1 = 'new value'
而oldObj.prop1 = 'old value'
,则会设置returnObj.prop1 = {type: 'update', data: 'new value'}
)
Update 2:(更新2:)
It gets truely hairy when we get to properties that are arrays, since the array [1,2,3]
should be counted as equal to [2,3,1]
, which is simple enough for arrays of value based types like string, int & bool, but gets really difficult to handle when it comes to arrays of reference types like objects and arrays.
(当我们进入数组属性时,它确实变得毛骨悚然,因为数组[1,2,3]
应该算作等于[2,3,1]
,对于基于值的类型(如字符串, int&bool,但是当涉及到引用类型的数组(例如对象和数组)时,就变得很难处理。)
Example arrays that should be found equal:
(应该找到相等的示例数组:)
[1,[{c: 1},2,3],{a:'hey'}] and [{a:'hey'},1,[3,{c: 1},2]]
Not only is it quite complex to check for this type of deep value equality, but also to figure out a good way to represent the changes that might be.
(检查这种类型的深度值相等不仅很复杂,而且要找到表示可能发生的更改的好方法。)
ask by Martin Jespersen translate from so