0

If you run the code snippet below you can observe the following: at first console.log() it print 0,Jhon after I modified the first element of the first array the same change is also reversed on the object in the second list, why? its possible to avoid this?

This is a sample of this problem:

var myArray = [{
    id: 0,
    name: "Jhon"
  },
  {
    id: 1,
    name: "Sara"
  },
  {
    id: 2,
    name: "Domnic"
  },
  {
    id: 3,
    name: "Bravo"
  }
];
var a = [];
a.push(myArray[0]);
console.log(a);
myArray[0].name = 'TEST';
console.log(a);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64

1 Answers1

1

If you dont want it to be by reference, you can use spread syntax

a.push({...myArray[0]});

complete code:

var myArray = [{
    id: 0,
    name: "Jhon"
  },
  {
    id: 1,
    name: "Sara"
  },
  {
    id: 2,
    name: "Domnic"
  },
  {
    id: 3,
    name: "Bravo"
  }
];
var a = [];
a.push({...myArray[0]});
console.log(a);
myArray[0].name = 'TEST';
console.log(a);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Yosef Tukachinsky
  • 5,570
  • 1
  • 13
  • 29