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);

5
  • 1
    Because they're two references to the same mutable object. If that's not the behaviour you want, push a copy into a. Commented Feb 24, 2020 at 8:34
  • can you provide a sample of what you mean ? Commented Feb 24, 2020 at 8:35
  • 2
    See How do I correctly clone a JavaScript object? Commented Feb 24, 2020 at 8:36
  • This one has a Explanation Read this Commented Feb 24, 2020 at 8:41
  • @jonrsharpe thanks , finally it work , the clone function is very useful Commented Feb 24, 2020 at 9:04

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.