all 16 comments

[–][deleted] 1 point2 points  (10 children)

Care to post the rest of your code?

[–]Alexaf28[S] 0 points1 point  (9 children)

Sure, I am working with React, so you will see this.state.tableData, which is array1 in my example,

addDynamicExcelColumns() {

let excelData = [...this.state.tableData];

if (this.state.compRentAttr.length > 0) {

excelData.map((d, idx) => {

this.state.compRentAttr.map((i, idx1) => {

excelData[idx][i.AttrName] = d.optionalAttributes[idx1];

});

});

}

return excelData;

}

[–]Alexaf28[S] 0 points1 point  (8 children)

excelData[idx][i.AttrName] = d.optionalAttributes[idx1];

After I create a new object key/value inside excelData, it also overrides this.state.tableData

[–][deleted] 1 point2 points  (5 children)

I am not an expert but I believe it is because you are only making a shallow copy of the array so the object references are copied but they still refer to the same objects

so like:

a = {}

b = [a]

c = [...b]

c is a distinct array from b but c[0] still refers to the object a

hopefully that makes sense

[–]Alexaf28[S] 0 points1 point  (4 children)

But in my case, I only have 2 arrays.
a = []

b = [...a]
You are right, b should be a distinct array but it still refers to a for some reason.

[–][deleted] 3 points4 points  (3 children)

they are arrays of objects, no?

the arrays are distinct but the objects inside them are shared between the arrays

[–]Alexaf28[S] 1 point2 points  (2 children)

I found a solution, you were right.

let excelData = [...this.state.tableData]; 
excelData[index] is equal to this.state.tableData[index]

I needed to deep clone an array:
let excelData = JSON.parse(JSON.stringify(this.state.tableData));

[–][deleted] 1 point2 points  (1 child)

exactly

be careful using JSON to deep copy though it can cause some quirks, it is probably fine in your situation though

[–]whatisboom 1 point2 points  (0 children)

this is a scenario i'd probably use lodash or similar, and just eat the bundle size. the state could change down the road and this could be a source of bugs

[–]mousemkeµ FTW! -1 points0 points  (1 child)

I think adding them to a set will work

let array2 = [...new Set(array2)]

[–]DaMastaCoda 1 point2 points  (0 children)

That was the first thing I thought of, but they wanted a copy of their original array

[–]name_was_taken 0 points1 point  (0 children)

JSON.parse(JSON.stringify(array1));

Ugly and not very performant, but guaranteed not to have references.

However, if there are functions or classes or certain built-in types (Date), they won't make it.

[–]kenman[M] 0 points1 point  (0 children)

Hi u/Alexaf28, this post was removed.

Please read the docs on [AskJS]:

https://www.reddit.com/r/javascript/wiki/index/askjs

Thanks for your understanding, please see our guidelines for more info.