2010-07-08 165 views
4

我有一些數組收集到的對象。出於各種原因,相同的對象也附加到某些DOM元素。有時我需要更新其中的一個對象。最簡單的方法是在數組中找到與我通過AJAX得到新值相同的id屬性的對象,然後替換它。但是,這當然會創建一個新對象,並且附加到DOM元素的對象不再相同。這意味着如果我將它們進行比較,它們不再是同一個對象。JavaScript:如何高效替換對象的所有值而不替換對象

我最簡單的如何可以替換的新對象的值正確的對象,而無需更換實際的對象? (因此,參考保持不變)的東西,我不想

var values = [{id:1, name:'Bob'}, {id:2, name:'Alice'}, {id:3, name:'Charlie'}]; 
var bar = values[2]; 
console.info(bar === values[0]); // True 

var newValue = {id:1, name:'Dave'}; 
// Somehow find the index of the object with id==3 
values[2] = newValue; 
console.info(bar === values[2]); // False, should still be true 

實例只有這樣我能想到的是通過與一個foreach什麼物體循環,但希望能有一些內置到JavaScript或jQuery,或者允許更高效或至少更乾淨的代碼。

回答

6

可以遍歷的新的值,並設定他們在舊:

for (i in newValue) { 
    oldValue[i] = newValue[i]; 
} 
+0

'$ .extend(oldValue,newValue)'似乎在更清晰的代碼中也是這樣做的,但我想它在後臺執行類似的操作:) – Svish 2010-07-08 10:14:51

+0

不要忘記'for中的'var'關鍵字var我在newValue){' – Dong 2015-07-22 04:38:25

2

你可以使用手柄/身上的花紋,所以數組中的對象只有一個屬性,它具有該對象的所有屬性:

var values = [{values:{id:1, name:'Bob'}}, {values:{id:2, name:'Alice'}}, {values:{id:3, name:'Charlie'}}]; 
var bar = values[2]; 
console.info(bar === values[0]); // True 

var newValue = {id:1, name:'Dave'}; 
// Somehow find the index of the object with id==3 
values[2].values = newValue; // set the values of the object, not the object 
console.info(bar === values[2]); // Still true 
1

我建議您在替換數組中的對象的同時替換附加到DOM元素的對象。這樣,比較仍然成立。

如果這是不可能的,那麼在你的例子,我們可以看到,你只有真正取代name財產。所以你只需要將Ajax對象的name屬性複製到Array對象。