0
let fulfillmentMessages = []
let multipleRides = formats.text_message
multipleRides.payload.data.text = predefined_responses.intent_report_lost_credential_confirmation_yes.case_ids.response

console.log("Multiple rides Message")
console.log(JSON.stringify(multipleRides))

let noRides = formats.text_message;
noRides.payload.data.text = predefined_responses.intent_report_lost_credential_confirmation_yes_2.response;

console.log("Multiple rides Message after")
console.log(JSON.stringify(multipleRides))

fulfillmentMessages.push(multipleRides)
fulfillmentMessages.push(noRides)

console.log("Going to send these messages")
console.log(JSON.stringify(fulfillmentMessages))

After this code executes multipleRides and noRides have same values in it and array contains the same value twice. Can someone please explain what I am doing wrong here?

  • 2
    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) – CertainPerformance Dec 14 '18 at 00:50

1 Answers1

0

The main problem here is that both variables, multipleRides and noRides, are referencing the same object, formats.text_message and thus, multipleRides.payload.data is the same object as noRides.payload.data. For that reason, the value stored in multipleRides.payload.data.text is overwritten by the assignment to noRides.payload.data.text. In JavaScript objects are copied by reference and not by value. You will need to do a deep clone of formats.text_message. A shallow copy wont be enough, due to how deep that text is.

This article will give you some hints for doing a deep clone. My advice is to use lodash, the code will be:

const _ = require('lodash')

let fulfillmentMessages = []
let multipleRides = _.cloneDeep(formats.text_message)
multipleRides.payload.data.text = predefined_responses.intent_report_lost_credential_confirmation_yes.case_ids.response

console.log("Multiple rides Message")
console.log(JSON.stringify(multipleRides))

let noRides = _.cloneDeep(formats.text_message);
noRides.payload.data.text = predefined_responses.intent_report_lost_credential_confirmation_yes_2.response;

console.log("Multiple rides Message after")
console.log(JSON.stringify(multipleRides))

fulfillmentMessages.push(multipleRides)
fulfillmentMessages.push(noRides)

console.log("Going to send these messages")
console.log(JSON.stringify(fulfillmentMessages))

You could also use JSON.parse(JSON.stringify(formats.text_message))

I hope this helps!

JoshuaCS
  • 2,524
  • 1
  • 13
  • 16