4

With an array of Javascript objects, I want to edit some values, then get an array of changed objects.

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

How to achieve the following?

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

[Edited]
This question is not a duplicate of How do you clone an array of objects using underscore?

The answer provided there answered that question (how to clone), but does not answer my question (how to clone and know the difference).

The DEMO in this question uses the trick in that answer, and demostrated that it cannot find the wanted difference.

Community
  • 1
  • 1
Ksthawma
  • 1,257
  • 1
  • 16
  • 28
  • 8
    Please stop using "JSON" when you refer to Javascript objects. There is no JSON in your question. – Tomalak Feb 08 '15 at 07:55
  • I've already removed the duplicate. Related reading: http://stackoverflow.com/q/13147278, especially [this answer](http://stackoverflow.com/a/19547466). – Tomalak Feb 08 '15 at 08:18

1 Answers1

1

Quick and dirty solution? Use JSON.stringify to deep-compare objects.

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))

Correct solution? Implement something like the uniqArrays discussed in this question:

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

Community
  • 1
  • 1
Guilherme Rodrigues
  • 2,818
  • 1
  • 17
  • 22