I have 3 array's that are copies of each other using slice(). After declaring each, I only append an attribute to data array called 'total'. When I console log, all the declared arrays have the new attribute 'total' present. Why is this? The only variable that should have total attribute is data. I used slice because that create a new separate array for each variable.

 const cData = (4093) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
 {…}, {…}, {…}, 
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
 {…}, {…}, {…}, …];
  //Side note: cData is actually an array of objects with key values
  //cData[2] would look like the below code.
  {Area: "NORTHEAST AREA", District: "CONNECTICUT CS 
  DISTRICTCT", Unit: "WORTHINGTON", Finance Number: "249656", Zip: 
  "01026", …}

 const data = cData.slice();
 var dataArea = data.slice();

 data[2]['total'] = 22; //When I console log all 3 variables have 
                        //total attribute appended

 console.log(cData[2]);            //When I console.log, all 3 variables 
 console.log(data[2]); //have total attribute appended
 console.log(dataArea[2]);

Why is this the case? Slice creates new array for each varible. I was expecting that only the variable 'data' would have appended total.

1 Answers

0
brk On

Since slice is creating a shallow copy of the original array , You can use JSON.parse & JSON.stringify to create a deep copy and then add new key to the array

let cData = [{
  Area: "NORTHEAST AREA",
  District: "CONNECTICUT CS DISTRICTCT",
  Unit: "WORTHINGTON ",
  FinanceNumber: "249656 ",
  Zip: "01026"
}, {
  Area: "NORTHEAST AREA",
  District: "CONNECTICUT CS DISTRICTCT",
  Unit: "WORTHINGTON ",
  FinanceNumber: "249656 ",
  Zip: "01026"
}, {
  Area: "NORTHEAST AREA",
  District: "CONNECTICUT CS DISTRICTCT",
  Unit: "WORTHINGTON ",
  FinanceNumber: "249656 ",
  Zip: "01026"
}]

const data = JSON.parse(JSON.stringify(cData))

data[2]['total'] = 22;

console.log(cData[2]);
console.log(data[2]);