Deep copy an array in Angular 2 + TypeScript
Check this:
let cloned = source.map(x => Object.assign({}, x));
Cloning an array in Javascript/Typescript
Clone an object:
const myClonedObject = Object.assign({}, myObject);
Clone an Array:
- Option 1 if you have an array of primitive types:
const myClonedArray = Object.assign([], myArray);
- Option 2 - if you have an array of objects:
const myArray= [{ a: 'a', b: 'b' }, { a: 'c', b: 'd' }];
const myClonedArray = [];
myArray.forEach(val => myClonedArray.push(Object.assign({}, val)));
Copy array of Objects in angular 2
But the problem is when I copy it, and I want to change the second
array, the first array is also changing
That is because the objects inside both the arrays are sharing same reference. To perform a deep copy try the following :
let persons2 = person.map(x => Object.assign({}, x));
Or
let person2 = JSON.parse(JSON.stringify(person));
How to deep clone array in typescript
Try to this ..
Remove this line from your code.
this.timeList = this.staticTime;
And add this line..
this.timeList = JSON.parse(JSON.stringify(this.staticTime));
take copy of an array without affecting original array in Angular 2
Assuming you are using ES6 you can use load lodash for deep copy
this.array1= _.cloneDeep(data.Result);
this.array2= _.cloneDeep(data.Result);
or use object.assign
this.array1= data.Result.map(function(obj) {
Object.assign({}, obj)
})
this.array2= data.Result.map(function(obj) {
Object.assign({}, obj)
})
Angular2 - Clone array of typed Object
I like to use this clone function
const clone = obj =>
Array.isArray(obj)
? obj.map(item => clone(item))
: obj instanceof Date
? new Date(obj.getTime())
: (typeof obj === 'object') && obj
? Object.getOwnPropertyNames(obj).reduce((o, prop) => ({ ...o, [prop]: clone(obj[prop]) }), {})
: obj;
See a demo here
https://stackblitz.com/edit/typescript-qmzgf7
If it is an array it returns an array of each item cloned, if it is a date it creates a new date, if it is an object if reduces the properties onto a new object with each property cloned. If none of these it is a value object or a function and just return it.
How to clone array of objects TypeScript?
The spread operator returns the individual items of the array. If these are already objects, then it's returning the references to those objects. It's the []
part that is creating a new array. Thus you have a new array, but it will still contain the same object references, so this.plans[0].oper()
will call this.plansCopy[0].oper()
at the same time as well.
Instead you need to clone each individual object. There are a lot of different ways to do this (create deep copy of the array or individual objects). If you only need one level of cloning you can do:
this.plansCopy = this.plans.map(obj => ({...obj}));
This will create a new array where each element is a copy of each object.
Angular : How to copy one array to another?
Try like this
setOrders() {
this.cloneOrders= [...this.orders];
}
Happy coding !!
Related Topics
How to Add a Class to a Dom Element in JavaScript
How to Send a Message to a Particular Client with Socket.Io
How JavaScript Closures Are Garbage Collected
How to Load Image Files with Webpack File-Loader
Get Query String Parameters Url Values with Jquery/JavaScript (Querystring)
How to Access Object Property with Invalid Characters
How to Set a Cookie with Expire Time
How Is a Promise/Defer Library Implemented
The Preferred Way of Creating a New Element with Jquery
Reactjs: Prevent Multiple Times Button Press
Passing Variables to the Next Middleware Using Next() in Express.Js
Advanced JavaScript: Why Is This Function Wrapped in Parentheses
Difference Between "Process.Stdout.Write" and "Console.Log" in Node.Js
How to Display Binary Data as Image - Extjs 4
How to Support Promises in Internet Explorer 11
Use Jquery to Scroll to the Bottom of a Div with Lots of Text