1

I'm working on a Alexa Skill lambda and have created small code fragment to illustrate my problem:

exports.handler = function(event, context)
{
    //CREATE A MODEL
    var model1 = {"endpoints":[ ]};

    //CREATE ANOTHER MODEL  
    var model2 = {"endpointid": "stuff"};

    //CREATE THE RESULT

    var result = model1;
    model2.endpointid="switch1";
    result.endpoints.push(model2);

    model2.endpointid="switch2";
    result.endpoints.push(model2);

    var  json = JSON.stringify(result);
    context.succeed({json});
};

Response:

{
  "json": "{\"endpoints\":[{\"endpointid\":\"switch2\"},{\"endpointid\":\"switch2\"}]}"
}

Question: Why do I get two of the same endpointids?

eebbesen
  • 5,070
  • 8
  • 48
  • 70
John
  • 21
  • 7
  • You're pushing the *reference* to `model2` into the `endpoints` array, not a copy of the object. In fact, at the end of the function body, `result` and `model1` will be *exactly* the same, because `result` is a reference to `model1` (it's actually a bit more complicated than that). You can read more here: [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/q/518000/1765851). – Sven May 05 '18 at 14:43
  • Any suggestions as how to change the code? So far my solution are ugly or still produce the dame results – John May 05 '18 at 16:08
  • This works but I do find it all that elegant: – John May 05 '18 at 17:45

2 Answers2

0

This works but I do not find it all that elegant:

exports.handler = function(event, context)
{
    //CREATE A MODEL
    var model1 = {"endpoints":[ ]};

    //CREATE ANOTHER MODEL  
    var model2 = {"endpointid": "stuff"};

    //CREATE THE RESULT

    model1.endpoints.push(model2);
    model1.endpoints.push(model2);
    model1.endpoints[0]="switch1";
    model1.endpoints[1]="switch2";

     var  json = JSON.stringify(model1);
   context.succeed({json});

Response: "json": "{\"endpoints\":[\"switch1\",\"switch2\"]}"

John
  • 21
  • 7
0

Definitely a bit hard to get your head around if you are new to JAVA and node.js:

  exports.handler = function(event, context)
   {
      //CREATE A MODEL
      var model1 = {"endpoints":[ ]};

      //CREATE ANOTHER MODEL  
      var model2 = {"endpointid": "stuff","friendly Name": "name"};

     //CREATE THE RESULT


     var  _copy1ofModel2 =JSON.parse (JSON.stringify (model2));
     var  _copy2ofModel2 =JSON.parse (JSON.stringify (model2));

     _copy1ofModel2.endpointid = "switch 1";
     _copy2ofModel2.endpointid = "switch 2";

     model1.endpoints.push(_copy1ofModel2);
     model1.endpoints.push(_copy2ofModel2);


    var  json = JSON.stringify(model1);
    context.succeed({json});

};

Response: { "json": "{\"endpoints\":[{\"endpointid\":\"switch 1\",\"friendly Name\":\"name\"},{\"endpointid\":\"switch 2\",\"friendly Name\":\"name\"}]}".

Thanks to eebbesen for getting me to look in the right direction.

John
  • 21
  • 7