Reputation: 335
In Component, I made http call to get all assignees from Backend.
Component :-
const req = this.assigneeService.getAssignees();
req.subscribe(
data => {
this.assignees = data['data'];
// On response json will be like below
[
{
name:"Name 3",
id:1,
status:"Not_Assigned"
},
{
name:"Archana",
id:2,
status:"Not_Assigned"
}
]
},
err => {
}
);
On click of button,the below function will call and create say objectM. Now assume I have created 2 more same object say objectM1 and objectM2 with same method.
public addObj1(): void {
let asignees1 = this.assignees.slice(0);
let objectM = new Module();
objectM.assignees = asignees1;
}
//onchange funtion where object is selected Object, action as string and id of user
changeAssigneeState(object, action, assigneeId ) {
for (let a of object.assignees) {
if (a.id == assigneeId) {
a.status = action;
}
}
}
On changing the assignee.status of id 1 in objectM. It affects objectM1 and objectM2 assignee.status of same id.
Please help me out. Thanks in advance.
Upvotes: 0
Views: 263
Reputation: 29705
You could also do it using Object.assign()
newAssignes = [];
this.assignees.forEach((assignee, i) => {
this.newAssignes[i] = Object.assign({}, assignee)
});
Upvotes: 0
Reputation: 396
deep clone of array objects will help you out.try this,
let asigneesData = JSON.parse(JSON.stringify(this.assignees));
Upvotes: 1
Reputation: 832
let asignees1 = this.assignees.slice(0);
clones array but objects inside have references to the objects in original array, you need to get deep clone of array of objects, you can do it using this simple trick:
let asignees1 = JSON.parse(JSON.stringify(this.assignees));
Then you will have cloned array with no references to original array.
Upvotes: 4