javascript - Clone object's properties by reference -


my data object:

var data = {   foo: {     bar: 42   },   baz: true,   x: 1,   y: 2 }; 

now i'd like send object json string. but before sending, i'd modify object and still keeping original one.

var json = data; json.foo = json.foo.bar; json.id = json.baz; delete json.baz; 

of course modify data object, too.

is possible create second object same structure first one, allows rename / delete properties without changing first object?

i know this:

var json = {   foo: data.foo.bar,   id: data.baz,   x: data.x,   y: data.y }; 

but imagine data object contains 50 properties , want change 2 of them.

and don't want use jquery.copy or angular.copy because of performance reasons (they create real copies - shouldn't necessary).

maybe there's ?

var json = {   foo: data.foo.bar,   id: data.baz }; json = merge(json, data); delete json.baz; 

thank you! :)

you can use angular.extend() or jquery.extend() copy original object's own properties. i.e. shallow copy

var json = angular.extend({}, data); json.foo = data.foo.bar; json.id = data.baz; delete json.baz; 

or

var json = angular.extend({}, data, {   foo: data.foo.bar,   id: data.baz }); delete json.baz; 

note following won't work because data's foo overwrite first argument object's foo.

var json = angular.extend({   foo: data.foo.bar,   id: data.baz }, data); delete json.baz; 

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -