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.
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.
Share Improve this question edited Mar 26, 2012 at 20:16 stinkycheeseman asked Mar 26, 2012 at 20:05 stinkycheesemanstinkycheeseman 45.8k7 gold badges31 silver badges49 bronze badges 2- 1 What about unsetting those properties afterward? – Sergio Tulentsev Commented Mar 26, 2012 at 20:07
- I can do that, it's just that I'd prefer not to waste the time and resources copying the property. For instance, if the value for a certain property was a large array I'd prefer not to copy it at all. – stinkycheeseman Commented Mar 26, 2012 at 20:13
2 Answers
Reset to default 11jQuery.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" }
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 a or an array of keys
var clone = _.omit(object, 'bim');
// { "foo":"bar" }