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

4
  • 1
    What does console.log(result) after the loop finishes show? Commented Apr 6, 2018 at 22:41
  • @ScottMarcus you are right problem is not about this part of code. Problem is in mocha. I try to use this array in a test but it uses last element always I will check it again. Commented Apr 6, 2018 at 22:50
  • @MehmetKemalBayer, move var obj = {}; declaration out of for loop and declare before for loop Commented Apr 6, 2018 at 22:56
  • all your base are belong to us Commented Apr 6, 2018 at 23:09

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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);
}

1 Comment

Thank you, the problem was about the other part of the code that calls the part I wrote above. I solved it by using let there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.