Ignore a property while using jquery $.extend()?

匿名 (未验证) 提交于 2019-12-03 08:36:05

问题:

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.

回答1:

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" } 


回答2:

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" } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!