【问题标题】:Find changed objects in an array of objects在对象数组中查找更改的对象
【发布时间】:2015-02-08 07:53:38
【问题描述】:

使用一组 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.

DEMO

如何实现以下?

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}]

[已编辑]
这个问题不是How do you clone an array of objects using underscore?的重复问题

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

这个问题中的DEMO使用了那个答案中的技巧,并证明它找不到想要的差异。

【问题讨论】:

标签: javascript underscore.js


【解决方案1】:

又快又脏的解决方案?使用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))

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

Finding nested duplicate arrays in JavaScript. (Nested Array uniq in lodash/underscore)

【讨论】:

  • JSON.stringify 保证排序顺序吗?它知道{x:1,y:2}{y:2,x:1} 相同?
  • 我猜不是。这就是为什么你应该使用正确的解决方案:)
  • 如果你真的想弄脏,你可以排序键! gist.github.com/tonylukasavage/5555476
  • 我知道这已经相当老了,但 lodash 的 differenceWith 结合 isEqual 对我来说效果很好。 (lodash.com/docs/4.17.11#differenceWith)
猜你喜欢
  • 1970-01-01
  • 2021-01-15
  • 1970-01-01
  • 1970-01-01
  • 2018-08-13
  • 2017-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多