2012-03-26 47 views
9

是否有克隆對象的有效方法,但遺漏了指定的屬性?理想情況下,不需要重寫$ .extend函數?

var object = { 
    "foo": "bar" 
    , "bim": Array [1000] 
}; 

// extend the object except for the bim property 
var clone = $.extend({}, object, "bim"); 
// = { "foo":"bar" } 

我的目標是通過不復制我不打算使用的東西來節省資源。

+1

那麼後來如何取消設置這些屬性呢? – 2012-03-26 20:07:36

+0

我可以做到這一點,這只是我不想浪費時間和資源複製財產。例如,如果某個屬性的值是一個大數組,我寧願不要複製它。 – stinkycheeseman 2012-03-26 20:13:30

回答

9

jQuery.extend需要無限數量的參數,因此無法重寫它以適合您的請求格式,而不會破壞功能。

你可以,但是,易擴展後刪除屬性,使用delete操作:

var object = { 
    "foo": "bar" 
    , "bim": "baz" 
}; 

// extend the object except for the bim property 
var clone = $.extend({}, object); 
delete clone.bim; 
// = { "foo":"bar" } 
+0

啊,所以沒辦法壓制某個屬性?我試圖不花太多時間/資源來複制我不打算使用的東西。 – stinkycheeseman 2012-03-26 20:17:22

+2

@stinkycheeseman不是沒有創建一個新的實現。這裏是'jQuery.extend'的註釋源代碼,以防萬一您感興趣:http://james.padolsey.com/jquery/#v=git&fn=jQuery.extend – 2012-03-26 20:20:00

+0

我有同樣的要求,只是因爲哈希包含「父母「,並且父母再次指向孩子,並且它進入無限循環,所以當我執行深度複製時,我也希望避免像」父母「這樣的密鑰 – 2013-05-21 10:15:41

0

可以歸檔你想要麼pickunderscoreomit什麼,它們都允許做的副本一個對象並過濾源對象中某些要在複製/克隆中包含或省略的鍵:

var object = { 
    "foo": "bar" 
    , "bim": Array [1000] 
}; 

// copy the object and omit the desired properties out 
// _.omit(sorceObject, *keys) where *keys = key names separated by coma or an array of keys 
var clone = _.omit(object, 'bim'); 
// { "foo":"bar" }