Reputation: 45757
Is there an efficient way to clone an object yet leave out specified properties? Ideally without rewriting the $.extend function?
var object = {
"foo": "bar"
, "bim": Array [1000]
};
// extend the object except for the bim property
var clone = $.extend({}, object, "bim");
// = { "foo":"bar" }
My goal is to save resources by not copying something I'm not going to use.
Upvotes: 11
Views: 7664
Reputation: 1900
You can archive what you want with either pick or omit from underscore, they both allow to make a copy of an object and filter certain keys from the source object to be included or omitted in the copy/clone:
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" }
Upvotes: 0
Reputation: 349042
jQuery.extend
takes an infinite number of arguments, so it's not possible to rewrite it to fit your requested format, without breaking functionality.
You can, however, easily remove the property after extending, using the delete
operator:
var object = {
"foo": "bar"
, "bim": "baz"
};
// extend the object except for the bim property
var clone = $.extend({}, object);
delete clone.bim;
// = { "foo":"bar" }
Upvotes: 11