2015-02-08 57 views
2

使用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?

答案只要回答了這個問題(如何克隆)的副本,但不回答我的問題(如何克隆和了解區別)。

在這個問題中的演示使用該答案中的技巧,並且演示了它找不到想要的區別。

+8

請停止使用「JSON」當你是指JavaScript對象。你的問題中沒有JSON。 – Tomalak 2015-02-08 07:55:43

+0

我已經刪除了重複。相關閱讀:http://stackoverflow.com/q/13147278,尤其是[這個答案](http://stackoverflow.com/a/19547466)。 – Tomalak 2015-02-08 08:18:03

回答

0

快速骯髒解決方案?使用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)

+0

'JSON.stringify'保證排序順序嗎?它知道'{x:1,y:2}'與'{y:2,x:1}'相同嗎? – 2015-02-10 04:05:15

+0

我想不是。這就是爲什麼你應該使用正確的解決方案:) – firstdoit 2015-02-10 09:28:15

+0

如果你確實想得到真正的污垢,但是,你可以按鍵排序! https://gist.github.com/tonylukasavage/5555476 – firstdoit 2015-02-10 09:30:49