在对象数组中查找已更改的对象

4
使用Javascript对象数组,我希望编辑某些值,然后获取更改后的对象数组。
a=[{x:1,y:2},{x:2,y:4}];
b = _.clone(a);  
// When I change b, a is also changed.  I can no longer know the original a.

////////////////////////////////
a=[{x:1,y:2},{x:2,y:4}];
b = _.map( a, _.clone );
// When I change b, a is not changed, 
// but I cannot find only the changed JSONs.
// Every JSON between a and b are considered different.

演示

如何实现以下效果?

a=[{x:1,y:2},{x:2,y:4}];
b = SOME_CLONE_OF_a;
b[0].x=5;
DIFF(b,a)  // want to get [{x:5,y:2}]
DIFF(a,b)  // want to get [{x:1,y:2}]

[编辑]
这个问题并不是如何使用underscore克隆对象数组?的重复。

那里提供的答案回答了那个问题(如何克隆),但并没有回答我的问题(如何克隆并知道差异)。

这个问题中的DEMO使用了那个答案中的技巧,并演示了它无法找到想要的差异。


8
请在提到JavaScript对象时停止使用"JSON"这个词。你的问题中并没有涉及到JSON。 - Tomalak
我已经删除了重复项。相关阅读:https://dev59.com/NGcs5IYBdhLWcg3wGQDF,尤其是[这个答案](https://dev59.com/NGcs5IYBdhLWcg3wGQDF#19547466)。 - Tomalak
1个回答

1

快速而简单的解决方案?使用JSON.stringify来深度比较对象。

console.group('map');
a=[{x:1,y:2},{x:2,y:4}];
b = _.map( a, _.clone );  // https://dev59.com/bmEi5IYBdhLWcg3wuuUk
console.log( 'diff', _.difference(b,a) );  // all different
b[0].x=5;
console.log( 'a[0]', a[0] );  // a[0] does not change with b[0]
console.log( 'b[0]', b[0] );
console.log( 'diff', _.difference(b,a) );  // all different
console.groupEnd('map');

console.log(_.difference(_.map(a, JSON.stringify), _.map(b, JSON.stringify)))

console.log(_.map(_.difference(_.map(a, JSON.stringify), _.map(b, JSON.stringify)), JSON.parse))

console.log(_.difference(_.map(b, JSON.stringify), _.map(a, JSON.stringify)))

console.log(_.map(_.difference(_.map(b, JSON.stringify), _.map(a, JSON.stringify)), JSON.parse))

正确的解决方案?实现类似于在这个问题中讨论的uniqArrays:

在JavaScript中查找嵌套重复的数组。 (lodash/underscore中的嵌套数组uniq)


JSON.stringify 是否保证排序顺序?它知道 {x:1,y:2}{y:2,x:1} 是相同的吗? - Ksthawma
我猜不是。这就是为什么你应该使用正确的解决方案 :) - Guilherme Rodrigues
如果你真的想要深入了解,你可以对键进行排序!https://gist.github.com/tonylukasavage/5555476 - Guilherme Rodrigues
我知道这可能有点老了,但是lodash的differenceWith结合isEqual对我来说效果很好。(https://lodash.com/docs/4.17.11#differenceWith) - Greg Venech

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接