0

I am trying to push a json object to an array after adding one more key pair value to it, but the resulting array is wrong with the last value of the pair,

  console.log("Followers")
  console.log(his_followers);     
  var data = { 
  createdAt: 1555674703
  //some more key pair values exist here
  }    

  his_followers.forEach(uid => {
    var tdata = data
    tdata.target_user = uid.followed_by
   console.log('tdata')
    console.log(tdata);
    followers_data.push(tdata)
  })
  console.log('Followers data')
  console.log(followers_data);

and this the output,

Followers
[ { followed_by: 'ramk' },
  { followed_by: 'balk' } ]
tdata
{ createdAt: 1555674703,
  target_user: 'ramk' }
tdata
{ createdAt: 1555674703,
  target_user: 'balk' }
Followers data
[ { createdAt: 1555674703,
    target_user: 'balk' },
  { createdAt: 1555674703,
    target_user: 'balk' } ]

As you see the followers_data target_user is wrong.. I have no clue why this is happening, any help is appreciated.

Code Tree
  • 2,160
  • 4
  • 26
  • 39
  • what is in `his_Followers` ? – Kunal Mukherjee Apr 19 '19 at 12:12
  • it is in the output Followers [ { followed_by: 'ramk' }, { followed_by: 'balk' } ] – Code Tree Apr 19 '19 at 12:14
  • 1
    `tdata.target_user = uid.followed_by` updates `data` as well because they are both pointing to same reference. Try `var tdata = {...data}` to clone the object first – adiga Apr 19 '19 at 12:17
  • oh wow! I never knew that pointing the same reference..it is working now..thanks – Code Tree Apr 19 '19 at 12:20
  • 1
    Possible duplicate of [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – adiga Apr 19 '19 at 12:22

0 Answers0