1

i don't really understand what's happening here and would appreciate pointing out flaws in my assumptions:

 putUser: async (req, res, next) => {
        console.log('test1', req.body)
        let data = req.body
        data["local.password"] = 'xd121244212141243'
        console.log('test2', data)
        console.log('test3', req.body)

this block of code produces result as:

test1 { 'local.username': 'name','local.password': 'passwordToChange' }
test2 { 'local.username': 'name','local.password': 'xd121244212141243' }
test3 { 'local.username': 'name','local.password': 'xd121244212141243' }

So the question is, why does value of req.body changes ? Is this because we are pointing to the object instead of making new one ?

Dziejo
  • 13
  • 1
  • 4

3 Answers3

1

Is this because we are pointing to the object instead of making new one ?

Yup.

 let data = req.body

That copies the reference to the object from req.body to data, so they are both referencing the same object. To copy instead:

 let data = { ...req.body };
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

You are correct both data and req.body point to the same location in memory.

You could fix this in many ways see this question for most of them.

One way which I think should suit your specific case is

let data = JSON.parse(JSON.stringify(req.body))

though it isn't particularily efficient.

0

Yup, see this S.O. post about it.

Tl;dr: "Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object."

natn2323
  • 1,983
  • 1
  • 13
  • 30