Javascript 在对象数组中查找已更改的对象
对于Javascript对象数组,我想编辑一些值,然后获得一个更改对象数组Javascript 在对象数组中查找已更改的对象,javascript,underscore.js,Javascript,Underscore.js,对于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
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}]
[已编辑]这个问题不是重复的 这里提供的答案回答了这个问题(如何克隆),但没有回答我的问题(如何克隆并了解差异)
这个问题中的演示使用了该答案中的技巧,并演示了它无法找到想要的差异。快速肮脏的解决方案?使用
JSON.stringify
深入比较对象
console.group('map');
a=[{x:1,y:2},{x:2,y:4}];
b = _.map( a, _.clone ); // https://stackoverflow.com/questions/21003059/how-do-you-clone-an-array-of-objects-using-underscore
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))
正确的解决方案?执行与本问题中讨论的Uniqarray类似的操作:
当您引用Javascript对象时,请停止使用“JSON”。你的问题中没有JSON。我已经删除了副本。相关阅读:,尤其是。
JSON.stringify
是否保证排序顺序?它知道{x:1,y:2}
和{y:2,x:1}
是一样的,我想不是。这就是为什么您应该使用正确的解决方案:)但是,如果您确实想得到真正的污垢,您可以对密钥进行排序!我知道这是相当古老的,但洛达斯的差异与相结合的isEqual
对我来说效果很好。()