How can I copy an object and lose its reference in Angular?
With AngularJS, I can use angular.copy(object)
, but I\'m getting some error using that in An
Assuming you are using ES6, you can use var copy = Object.assign({}, original)
. Works in modern browsers; if you need to support older browsers check out this polyfill
update:
With TypeScript 2.1+, ES6 shorthand object spread notation is available:
const copy = { ...original }
For shallow copying you could use Object.assign which is a ES6 feature
let x = { name: 'Marek', age: 20 };
let y = Object.assign({}, x);
x === y; //false
DO NOT use it for deep cloning
Use lodash as bertandg indicated. The reason angular no longer has this method, is because angular 1 was a stand-alone framework, and external libraries often ran into issues with the angular execution context. Angular 2 does not have that problem, so use whatever library that you want.
https://lodash.com/docs#cloneDeep
I as well as you faced a problem of work angular.copy and angular.expect because they do not copy the object or create the object without adding some dependencies. My solution was this:
copyFactory = (() ->
resource = ->
resource.__super__.constructor.apply this, arguments
return
this.extendTo resource
resource
).call(factory)
You can clone the Array like
this.assignCustomerList = Object.assign([], this.customerList);
And clone the object like
this.assignCustomer = Object.assign({}, this.customer);
I needed this feature just form my app 'models' (raw backend data converted to objects). So I ended up using a combination of Object.create (create new object from specified prototype) and Object.assign (copy properties between objects). Need to handle the deep copy manually. I created a gist for this.