2

Do you have any idea why this code always adds the last object? Because I used

var obj = {} 

and

var newBase = Object.assign({}, baseJson)

but code always use the same reference?

module.exports = (csv, baseJson) => {

var lines=csv.split("\n");

var result = [];

var headers=lines[0].split(";");
for(var i=1;i<lines.length;i++){
    var obj = {};
    var newBase = Object.assign({}, baseJson);
    obj["case"] = "Scenario";
    obj["request"] = newBase;
    obj["response"] = {
        responseCode: "5",
        actionCode: "0",
        approvalCode: "98765X",
    }
    var currentline=lines[i].split(";");
    var responseTags = ["responseCode", "actionCode", "approvalCode"];      
    for(var j=0;j<headers.length;j++){

        headers[j] = headers[j].replace('\r','');
        currentline[j] = currentline[j].replace('\r','')
        if (headers[j] == "Scenario") {
            obj["case"] = currentline[j];
        }
        else if (responseTags.indexOf(headers[j]) > -1 ){
            obj["response"][headers[j]] = currentline[j];
        }
        else {
            saveValue(obj["request"], headers[j], currentline[j]);
        }
    }
    result.push(obj);

}

I tried almost everything but I could not manage to create a new object. It uses the same reference. This code is in node.js. Thank you

2 Answers2

1

Object.assign may not clone inner objects and it just takes same reference, try stringify and parse it.

 var newBase = JSON.parse(JSON.stringify(baseJson));

Refer to know more : What is the most efficient way to deep clone an object in JavaScript?

Manivannan
  • 3,074
  • 3
  • 21
  • 32
0

This is because Javascript vars scoped to functions, not blocks. Effectively in your code obj is declared outside of the loop and it's properties mutated.

let should solve the problem:

for(var i=1;i<lines.length;i++){
  let obj = {};
  ...
  result.push(obj);
}
Artem Koshelev
  • 10,548
  • 4
  • 36
  • 68