how to create a copy of the json object in javascript instead of a reference

advertisements

This question already has an answer here:

  • What is the most efficient way to deep clone an object in JavaScript? 53 answers

i have testdata.js file with json test data as below:

testdata.js file:

module.exports =

{ createHost: {

        name : "System-001",
        description: "Creating System",

    }

}

In another test, I am trying to create a variable called testcase1 with the above test data. Changing the property value in testcase1, changes the value in the testdata.js file json object.

it("Create a host", function(){
var testcase1 = testdata.createHost;

testcase1.name="sys-002";

console.log(testcase1.name);
console.log(testdata.createHost.name);
});

Response: sys-002 sys-002

My requirement is to create a copy of testdata instead of creating a reference. How can I do this?


Shortest way:

var copied = JSON.parse(JSON.stringify(object));