I have two arrays of objects
A = [{x: x1, y: y1 ...}, {x: x1, y: y1}];
and I am iterating over these upading
B.forEach((d, i) => d['x'] = A[i]['x']));
However, whenever I am now updating B, A
is updating as well.
Edit: Apparently the problem is not above, so here is all I do:
I have 3 arrays of objects, A, B, C
.
I initialize them as follows:
A = await d3.json(endpointA).then(res => res);
C = await d3.json(endpointB).then(res => res);
B = [...A];
They are the bound with .data(B)
to some svg elements with d3
and updated.
I am guessing they get referenced but while I have now a few months behind me, this is still my first javascript project so I am not 100% sure.
Any suggestions are very welcome!
Thank you!
CodePudding user response:
Your B
only clones array itself, but you also need to clone the objects inside the array:
B = [...A].map(o => Object.assign({}, o));
As @Pointy pointed out, this will only work if objects don't have nested objects.
For nested objects you'd need a deep cloning function:
B = cloneObj(A);
function cloneObj(obj)
{
const ret = Array.isArray(obj) ? [] : {};
for(let o in obj)
{
if (obj[o] && typeof obj[o] == "object")
ret[o] = cloneObj(obj[o]);
else
ret[o] = obj[o];
}
return ret;
}
CodePudding user response:
The basic issue is this:
B = [ ... A ];
That makes a shallow copy of A. Making deep copies of objects is, in the general case, pretty difficult because objects can have lots of "shapes". In your case, however, it's likely that the following trick will work:
B = A.map(v => JSON.parse(JSON.stringify(v)));
That uses the JSON facility to stringify each object in A, and then parse it back to an object. That trick does not always work; in particular, if an object has functions or various other data values that cannot be serialized to JSON, it will strip those values out of the objects.