Monday, 3 April 2017

changes two one Array always changing another one as well

For a project I need to import an Excel File, change the data to JSON, and reformat it in different ways to be readable for my application. One step involves splitting one line of the Excel into two different arrays which have to be changed individually.

But whatever I'm doing wrong - any changes to one of the Arrays changes not only the other array accordingly, but also my original data.

let data = [{
  value1: 1,
  value2: 2
}, {
  value1: 3,
  value2: 4
}]
let temp1 = [];
let temp2 = [];
for (let x of data) {
  temp1.push(x); //pushing x in array 1
  temp2.push(x); //pushing x as well in array 2
}
for (let x of temp1) {
  x.type = 'typeA'
}
for (let x of temp2) {
  x.type = 'typeB'
}
console.log(JSON.stringify(data));
console.log(JSON.stringify(temp1));
console.log(JSON.stringify(temp2));
//all three give the same result.

Does anybody know where my code went wrong?



via Torf

No comments:

Post a Comment