0

Today I have faced a new issue while coding in NodeJS I was fetching a record from DB which is an object which will contain an object array as well and I have assigned object array to a new variable lets call arr and I pushed a string into arr. And for some strange reasons, my original record also affected not sure why it has happened. I know about changing/reassigning an object will affect the original object but in this case am not sure why it has happened.

let original = {
  a: 1,
  branchIds: [ {
    _id: "abc",
    name: "abc"
   }]
};
let arr = original.branchIds;
arr.push("sa");
console.log(original);

JsFiddle Link http://jsfiddle.net/jdqmLzbv/4/

Kannan T
  • 1,639
  • 5
  • 18
  • 29
  • Your setting the variable `arr` to original.branchIds, so by calling `.push` on `arr` it's pushing another item into the array of variable `original`. What is unclear about this? – Ryan Wilson Jul 18 '18 at 18:25
  • @RyanWilson am pushing a new item on arr not to the original that is what am unclear about – Kannan T Jul 18 '18 at 18:29
  • 1
    But it *is* the original. Just assigning it to the variable does nothing. The value of an object is its reference, so you're pushing to the same array. – Andrew Li Jul 18 '18 at 18:31
  • @Kannan By setting `arr` = `original.branchIds` you are giving it a reference to the array held by `original` so any changes made affect the original, Zohaib's answer explains it along with a solution. – Ryan Wilson Jul 18 '18 at 18:32
  • @RyanWilson got it. Thanks – Kannan T Jul 18 '18 at 18:35

2 Answers2

3

You need to a copy of the array before modifying it:

let arr = original.branchIds.slice();
Xiaoy312
  • 14,292
  • 1
  • 32
  • 44
  • Updating the already exiting items will update in orignal array as well – Zohaib Ijaz Jul 18 '18 at 18:27
  • Indeed, as the new array still holds references to the very same object. If you need a deep copy, take a look here: https://stackoverflow.com/questions/6089058/nodejs-how-to-clone-a-object – Xiaoy312 Jul 18 '18 at 18:32
  • So what is the difference if i assign with .slice() method?. Could you please explain? – Kannan T Jul 18 '18 at 18:50
  • Try `arr[0].name = "qqq"` with both method and you will see the difference. This is because they references the same object: [Shallow copy VS Deep copy](https://cdn-images-1.medium.com/max/1600/1*6fjXVjxrpLWB_U3Gkz51MQ.png) – Xiaoy312 Jul 18 '18 at 21:24
3

You are using same reference and actually pushing into same array. Make a copy of it and orignal will not get updated

let original = {
  a: 1,
  branchIds: [ {
    _id: "abc",
    name: "abc"
   }]
};
let arr = original.branchIds.map(obj => ({...obj}));
arr.push("sa");
console.log(original);
console.log(arr);
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60