Issue
I have gone through several of the answers and I gather that this might be a logical error but I am not able to figure a way to achieve this.
I have to list of dictionaries in typescript/javascript. One is a copy of the other for tracking. When I am modifying one of the lists the other one gets modified too. Kindly explain a possible way to achieve the same
var a = new Array({"x":[2,3,14,5,7,8],"y":[7,8,9,10]})
//
var b = a.slice();
//I have tried different ways of slicing as well; for example: b = [...a]
b.filter(i=> i['x']= i['x'].filter(z=>z%2==0))
console.log(a,b)
This code modifies both the lists a and b. I want to achieve modification of b without affecting a is it possible?
Solution
You need to make a deep-copy of the source
There are different ways to create a deep-copy: e.g. check this Deep copy an array in Angular 2 + TypeScript
a simple way is to convert to JSON and back
var b = JSON.parse(JSON.stringify(a));
var a = new Array({"x":[2,3,14,5,7,8],"y":[7,8,9,10]})
var b = JSON.parse(JSON.stringify(a));
//I have tried different ways of slicing as well; for example: b = [...a]
b.filter(i=> i['x']= i['x'].filter(z=>z%2==0))
console.log(a, b)
Answered By - TmTron
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.