0

I face an behavior which I cant explain but reproduce. I created an array of objects as a source data. I declared an second array and passing the data from the first. Now I can manipulate the second array without losing the original data.

But as soon as I manipulate the second array the source array changed too.

Please refer to the console output.

  • The first console.log(person) before maniupulation of filterPerson (expected output ok).
  • The second console.log(person) after maniupulation of filterPerson (expected output not ok) Since I did not adressed the first array those data shouldn´t be touched at all.

Can somebody explain me this?

var person = [{"name": "Abby", "age": "22"}, {"name": "Paul", "age": "28"}, {"name": "Susi", "age": "19"} ]
var filterPerson = []

filterPerson = person

console.log(person)

for (var element of filterPerson) {
    if (element.age != 22) {
        element.age = 18
  }
}

console.log(person)

console.log(filterPerson)
ICoded
  • 319
  • 3
  • 18
  • 1
    Objects in JS are copied by reference. So `filterPerson = person` makes 2 variable pointing to same memory location. For your reference: https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object – Rajesh May 24 '22 at 10:25
  • Damn I did not know that. Thanks Rajesh, how can I deal with it in case I need both values? – ICoded May 24 '22 at 10:27
  • 1
    Check the linked post. You'll get what you need – Rajesh May 24 '22 at 10:27

0 Answers0