Hi I'm playing around with node.js and Javascript for an upcoming project. I have an array of template objects called templateValues.
Now I'd like to copy these two objects with altered id's into an new array myArray.
let templateValues = [{'id':1 , 'type': 'a'},{'id':2 , 'type': 'b'}];
let myArray = [];
for (let index = 0; index < 10; index++) {
myArray = myArray.concat(templateValues.map(e => {
e.id = Math.random(); // suppose this gives a unique id
return e;
}).slice(0));
}
console.log(myArray);
OUTPUT:
{id: 0.13413583461207668, type: "a"}
{id: 0.7426427992455211, type: "b"}
{id: 0.13413583461207668, type: "a"}
{id: 0.7426427992455211, type: "b"}
{id: 0.13413583461207668, type: "a"}
{id: 0.7426427992455211, type: "b"}
{id: 0.13413583461207668, type: "a"}
{id: 0.7426427992455211, type: "b"}
...
Why are the ids all the same even if I do slice(0) of the altered templateValues-array to get a "data-copy"?!
slice()makes a shallow copy, not a deep copy.